如何将参数传递给OnClickListener()?
找到我的听众了:
OnClickListener myListener = new OnClickListener()
{
@Override
public void onClick(View v)
{
//I want to reach params here
}
};
我有12个按钮,我不想为它们编写12个监听器,只需传递一个字符串给它们就好了,它们可以做完全不同的事情。
发布于 2012-05-16 16:31:57
使用您自己的自定义OnClickListener
public class MyLovelyOnClickListener implements OnClickListener
{
int myLovelyVariable;
public MyLovelyOnClickListener(int myLovelyVariable) {
this.myLovelyVariable = myLovelyVariable;
}
@Override
public void onClick(View v)
{
//read your lovely variable
}
};
发布于 2014-05-20 21:52:40
我知道这是一个迟来的答案,但希望它能帮助一些人。现有的答案在我的情况下都不起作用,但我最终使用了一个像按钮一样运作的图像的setTag功能。我的帐户信息在全局成员变量中,该变量是在活动开始时设置的。
在本例中,我设置了一个表,其中每一行都是一个帐户。单击图像时会显示帐户详细信息(图像只是一个信息图标)。
因此:
// prior code....
// NOTE: oneAccount is an object (AccountInfo) holding information about the account
// column with the "detail" arrow
image1 = new ImageView(this);
image1.setImageResource(R.drawable.info);
image1.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
image1.setPadding(15, 1, 15, 1);
image1.setTag(oneAccount);
// add a listener to go to that account detail on a click
image1.setOnClickListener(new TextView.OnClickListener() {
public void onClick(View v) {
// change the color to signify a click
v.setBackgroundColor(getResources().getColor(R.color.button_selected));
// get what we need out of the tag
AccountInfo thisAcct = (AccountInfo) v.getTag();
// your code would do other stuff here
}
});
// add the image to the table row
tr1.addView(image1);
发布于 2016-09-13 12:30:29
如果您有与视图相关联的静态内容,另一种选择是使用HashMap
将视图id映射到内容。
private static Map<Integer, String> idToStringMap = new HashMap<Integer, String>();
在onCreate
中初始化地图
idToStringMap.put(R.id.button1, "hello");
idToStringMap.put(R.id.button2, "world");
// ...
然后从onClick
中的视图id中获取值
public void onClick(View v) {
String myString = idToStringMap.get(v.getId());
}
这比使用一长串开关用例要干净一些。
https://stackoverflow.com/questions/10614696
复制相似问题