Creating a custom OnClickListener

后端 未结 4 517
无人及你
无人及你 2020-12-30 10:00

I have an ArrayList of Buttons where my OCL needs to know which index I has been pressed. The plan is something like this:

MyOnClickListener onClickListener          


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-30 10:50

    set setOnClickListener to Button as :

    buttonList.get(i).setOnClickListener(new MyOnClickListener(i));
    

    EDIT :

    I need to finish an activity in myOCL, how would I do that?

    for finishing Activity on Button Click from non Activity class you will need to pass Activity Context to your custom OnClickListener as :

    buttonList.get(i).setOnClickListener(new MyOnClickListener(i, Your_Current_Activity.this));
    

    and change the Constructor of your custom OnClickListener class to :

    int index;
    Context context; 
    public MyOnClickListener(int index,Context context)
    {
        this.index = index;
        this.context=context;
    }
    
    @Override
    public void onClick(View arg0) {
    
        // now finish Activity as\
        context.finish();
          //  OR
            // ((Activity)context).finish();
    }
    

提交回复
热议问题