Get context inside onClick(DialogInterface v, int buttonId)?

前端 未结 4 1343
悲哀的现实
悲哀的现实 2020-11-29 03:36

Getting the context inside onClick(View view), the callback for a button\'s onClickListener(), is easy:

view.getContext()
         


        
4条回答
  •  春和景丽
    2020-11-29 03:57

    Here is how you do it in case you

    1. do not want to have any anonymous class usage
    2. or having your activity/fragment implement the interface directly.

    Just simply,

    1. use dialogInterface object and cast it to Dialog object
    2. then call getContext()

    Example with DialogInterface.OnClickListener:

    DialogInterface.OnClickListener foo = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int which) {
            Dialog dialog  = (Dialog) dialogInterface;
            Context context = dialog.getContext();
            // do some work with context
        }
    };
    

    This will also work for the following interfaces as well, just use the first param DialogInterface dialogInterface and cast.

    • DialogInterface.OnCancelListener
    • DialogInterface.OnDismissListener
    • DialogInterface.OnKeyListener
    • DialogInterface.OnMultiChoiceClickListener
    • DialogInterface.OnShowListener

提交回复
热议问题