Want to change action bar icon when click on ok button of AlertDialog in Android Studio

Henry :

I have been trying to write something so that when an alertDialog popup, I click ok then login icon will be hidden, logout and settings icon will be visible. But I just can't get it to work. Hopefully someone can help me. I have been at it for quite sometime...

in MainActivity:

public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        // Login button
        if (id == R.id.loginButton){
            LoginDialog loginDialog = new LoginDialog();
            loginDialog.show(getSupportFragmentManager(), "loginDialog");

        }

        // Logout Button
        if (id == R.id.logoutButton){

        }

        // Setting Button
        if (id == R.id.settingsButton){

        }

        return super.onOptionsItemSelected(item);
    }

in LoginDialog class:

public class LoginDialog extends AppCompatDialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.login_dialog, null);

        builder.setView(view)
                .setTitle("Login")
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        /* I tried 
                           Menu menu = findItem(R.id.loginButton).setVisible(false); 
                           but that's not correct 
                           I tried this here because it works in MainActivity but not here */
                    }
                });
        return builder.create();
    }
}
Vitaly Kalenik :

Create interface

interface MyInterface{
    public void hideMenuItem();
}

Make Activity implement interface

class MainActivity implements MyInterface {

    @Override
    public void hideMenuItem(){
        menu.findItem(R.id.item_to_show).setVisible(false);
    }

So your DialogFragment's onClick looks like this

@Override
public void onClick(DialogInterface dialog, int which) {
    MyInterface myInterface = (MyInterface) getActivity();
    if(myInterface != null){
        myInterface.hideMenuItem();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=170607&siteId=1