How to start Activity in adapter?

前端 未结 8 1263
执念已碎
执念已碎 2020-11-27 03:16

I have a ListActivity with my customized adapter and inside each of the view, it may have some buttons, in which I need to implement OnClickListener. I need to

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 03:27

    callback from adapter to activity can be done using registering listener in form of interface: Make an interface:

          public MyInterface{
             public void  yourmethod(//incase needs parameters );
             }
    

    In Adapter Let's Say MyAdapter:

        public MyAdapter extends BaseAdapter{
           private MyInterface listener;
    
        MyAdapter(Context context){
            try {
                this. listener = (( MyInterface ) context);
                  } catch (ClassCastException e) {
                   throw new ClassCastException("Activity must implement MyInterface");
              }
    

    //do this where u need to fire listener l

              try {
                    listener . yourmethod ();
                } catch (ClassCastException exception) {
                   // do something
                }
    
          In Activity Implement your method:
    
    
             MyActivity extends AppCompatActivity implements MyInterface{
    
                    yourmethod(){
                    //do whatever you want
                         }
                         }
    

提交回复
热议问题