【发布时间】:2015-05-26 10:30:08
【问题描述】:
我有很多以编程方式创建的按钮,每个按钮对应一个特定的操作,我需要能够根据单击的按钮来识别和检索用户输入。界面如下:
我有 70 件类似的物品。
我读过
Dynamically creating Buttons and setting onClickListener
和
Implementing OnClickListener for dynamically created buttons in Android
但我不知道什么是正确的方法。例如,如果用户点击ButtonText is now set...,我必须能够检索到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
}
};
}
这是最好的方法吗?
【问题讨论】:
标签: java android android-layout onclicklistener