我有许多通过编程方式创建的按钮,每个按钮都对应于某个操作,并且我需要能够根据单击的按钮来识别和检索用户输入。用户界面如下:
我喜欢70件这样的东西。
我读了
Dynamically creating Buttons and setting onClickListener
和
Implementing OnClickListener for dynamically created buttons in Android
但是我不知道什么是正确的方法。例如,如果用户单击Button
文本,现在已设置...,则我必须能够检索EditText
的值,并且知道该分钟数与Andar carrito compra相符。
将tag
分配给Button
以识别屏幕上的索引,然后在视图层次结构中上移并检索EditText
值,是否正确?
到目前为止,这是我的代码:
for (int i = 1; i < types.length; i++) {
// ... more views created
// ......
Button enterBt2 = new Button(this);
// Set layout params and stuff for the button
enterBt2.setTag(i);
enterBt2.setOnClickListener(getOnClickDoSomething(enterBt2));
// ....
}
和
OnClickListener
:View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
Log.e(TAG, "O " + ExerciseRecord.TYPE.values()[((int) button.getTag())]);
// Obtain the value of the EditText with
LinearLayout ll = (LinearLayout) button.getParent();
ll.getChildAt(0); //The EditText
}
};
}
这将是最好的方法吗?
最佳答案
为按钮分配标签是正确的,以便识别
屏幕上的索引,然后在“视图”层次结构中上移并
检索EditText值?
这是一个选择。或者,您可以有一个实现该接口的类,添加一个带有String作为参数的构造函数。例如。
public class MyOnClickListener implements View.OnClickListener {
final String mValue;
public MyOnClickListener(String value) {
mValue = value;
}
public void onClick(View v) {
Log.e(TAG, "O " + mValue);
// Obtain the value of the EditText with button.getParent()....
}
}
关于java - 如何在自动创建的多个按钮上管理OnClickListener,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30455962/