问题描述
基本上我创建中的一个按钮,用于循环,我需要每个按钮返回时pressed不同的值。
Basically I am creating buttons within a for loop, I need each button to return a different value when pressed.
我原以为创造我自己的onClickListener()并传入需要的初始化时会工作参数的数据。它似乎有什么我想出了但没有语法错误,当按钮被点击运行时应用程序崩溃。
I had thought that creating my own onClickListener() and passing in the data needed as a parameter when it is initialized would work. It appears there are no syntax errors with what I came up with but when a button is clicked at run time the app crashes.
下面有什么,我已经得到了迄今为止的简化版本。
Heres a simplified version of what I've got thus far.
int counter = 1;
for( Program element : someList)
{
//some other code for dynamically creating textviews to stick the buttons in
//code which creates the buttons on the fly
moreInfo = new Button(this);
moreInfo.setText("More Info");
moreInfo.setOnClickListener(new DynamicOnClickListener(counter));
counter++;
}
自定义监听器类
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class DynamicOnClickListener implements OnClickListener
{
int counter;
public DynamicOnClickListener(int acounter) {
this.counter = acounter;
}
public void onClick(View v) {
Log.v("DynamicOnClickListener","1");
Toast.makeText(v.getContext(), counter, Toast.LENGTH_LONG).show();
}
}
所以理论上,如果这个工作的每个按钮将返回不同的号码,希望是有道理的。
So in theory if this worked each button would return a different number, hope that makes sense.
推荐答案
Toast.makeText
需要字符串资源ID作为第二个参数。您的计数器的值不是唯一的方式,您收到错误的有效资源ID。你需要传递一个字符串
而不是 INT
的,它会正常工作。
Toast.makeText
takes string resource id as a second argument. Your counter value is not a valid resource id that's way you are getting an error. You need to pass a String
instead of int
and it will work.
Toast.makeText(v.getContext(), String.valueOf(counter), Toast.LENGTH_LONG).show();
这篇关于Android的发展:传递参数到onClickListener()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!