简体   繁体   中英

how to set visibility of button from second activity in android

hello i have small problem with my android app I have two classes: MainActivity and ViewDialogStop.

public class ViewDialogStop extends MainActivity{
public void showDialogStop(Activity activity){

    final Dialog dialog = new Dialog(activity);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setCancelable(false);
    dialog.setContentView(R.layout.dialog_stop);


    ImageButton dialogButtonDone = (ImageButton) dialog.findViewById(R.id.btn_done);
    ImageButton dialogButtonExit = (ImageButton) dialog.findViewById(R.id.btn_exit);
    dialogButtonExit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });


    dialogButtonDone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Context ctx = v.getContext();
            stopNow(v);
        }
    });
    dialog.show();
}

}

and in main activity

public void stopNow(View view){
Context ctx = view.getContext();
Toast toast = Toast.makeText(ctx,
                "This works!",
                Toast.LENGTH_SHORT);

        toast.show();

        stopBtn.setVisibility(View.INVISIBLE);

    }

but every time i received this error: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference

Toast message works but I need to set up stopBtn INVISIBLE how can I do that?

Your approach will not work. You cannot access the View s in one Activity from another Activity . A better approach would be to have MainActivity launch ViewDialogStop using startActivityForResult() . Then ViewDialogStop can set a "result" with data that gets passed back to MainActivity when it finishes. In MainActivity you override onActivityResult() (which will be called when ViewDialogStop finishes) and you can examine the returned "data" and based on that, you can call stopNow() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM