创建自定义OnClickListener自定义、OnClickListener

2023-09-06 13:55:08 作者:一个超人

我有按钮的ArrayList在我的八达通卡公司需要知道哪些指标我一直pressed。 该计划是这样的:

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 = new MyOnClickListener() {

        @Override
        public void onClick(View v) {

            Intent returnIntent = new Intent();
            returnIntent.putExtra("deleteAtIndex",idx);
            setResult(RESULT_OK, returnIntent);
            finish();

        }
    };
    for (int i =0;i<buttonList.size();i++) {
        buttonList.get(i).setText("Remove");
        buttonList.get(i).setOnClickListener(onClickListener);
    }

如何我执行OCL都需要什么样子的?

How does my implementation of the OCL need to look like ?

目前我有这样的:

public class MyOnClickListener implements OnClickListener{

int index;

public MyOnClickListener(int index)
{
    this.index = index;
}

@Override
public void onClick(View arg0) {


}

}

不过,我不能确定什么,我需要做我的OCL的构造函数中,藏汉作为重写的onClick 的功能。

However, I am unsure of what I need to do within the constructor of my OCL, aswell as the overriden onClick function.

推荐答案

设置 setOnClickListener 来按钮:

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

编辑:

我需要完成的myOCL的活动,我将如何做到这一点?

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

有关按钮单击非活动类的整理活动,你将需要传递活动上下文到您的自定义OnClickListener为:

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));

和改变你的自定义的构造OnClickListener类:

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();
}