get Activity object while in View context

前端 未结 2 1959
醉梦人生
醉梦人生 2021-01-14 16:37

This is a followup to this post:

findViewById in a subclassed SurfaceView throwing RuntimeException

Based on Romain Guy\'s feedback (which I\'ll accept short

2条回答
  •  时光取名叫无心
    2021-01-14 17:01

    If you already know the Activity class your View is in, i.e. MyActivity, you can use the static member MyActivity.this from inside your View and its listeners, as in the following example:

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    MyActivity.this.finish();
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();
    

    which I've found in this Android tutorial:

    http://developer.android.com/guide/topics/ui/dialogs.html

    It worked wonders for me.

    PJ_Finnegan

提交回复
热议问题