How to start Activity in adapter?

前端 未结 8 1203
执念已碎
执念已碎 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:49

    First Solution:

    You can call start activity inside your adapter like this:

    public class YourAdapter extends Adapter {
         private Context context;
    
         public YourAdapter(Context context) {
              this.context = context;     
         }
    
         public View getView(...){
             View v;
             v.setOnClickListener(new OnClickListener() {
                 void onClick() {
                     context.startActivity(...);
                 }
             });
         }
    }
    

    Second Solution:

    You can call onClickListener of your button out of the YourAdapter class. Follow these steps:

    Craete an interface like this:

    public YourInterface{
             public void  yourMethod(args...);
    }
    

    Then inside your adapter:

        public YourAdapter extends BaseAdapter{
                   private YourInterface listener;
    
               public YourAdapter (Context context, YourInterface listener){
                        this.listener = listener;
                        this.context = context;
               }
    
               public View getView(...){
                    View v;
             v.setOnClickListener(new OnClickListener() {
                 void onClick() {
                     listener.yourMethod(args);
                 }
             });
    }
    

    And where you initiate yourAdapter will be like this:

    YourAdapter adapter = new YourAdapter(getContext(), (args) -> {
                startActivity(...);
            });
    

    This link can be useful for you.

    0 讨论(0)
  • 2020-11-27 03:50

    Simple way to start activity in Adopter's button onClickListener:

    Intent myIntent = new Intent(view.getContext(),Event_Member_list.class);                    myIntent.putExtra("intVariableName", eventsList.get(position).getEvent_id());
                    view.getContext().startActivity(myIntent);
    
    0 讨论(0)
提交回复
热议问题