我正在使用android以编程方式和动态添加一些元素(按钮和文本视图)。我还需要为每个按钮设置setOnClickListener事件,并从该事件中执行一些单击按钮的操作:
do
{
EditText txt1 = new EditText(this);
EditText txt2 = new EditText(this);
Button showtxt = new Button(this);
linearLayout.addView(showtxt );
linearLayout.addView(txt1);
linearLayout.addView(txt2);
showtxt.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String aaa= txt1 .getText().toString();//HOW TO ACCESS txt1 and txt2 from here
String bbb= txt2 .getText().toString();
}
}
}
while(somecondition)我几乎是android的新手。如何在点击回调函数中访问txt1和txt2?
发布于 2012-06-24 06:33:48
您需要定义变量,其中它们将具有类范围的范围:
public class Example extends Activity {
EditText txt1;
EditText txt2;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
txt1 = new EditText(this);
txt2 = new EditText(this);
...现在,您的onClick函数将能够看到txt1和txt2。
或
由于您似乎要在一个按钮中创建大量的txt1和txt2,因此可以向您的LinearLayout传递一个对其EditTexts的引用:
do {
...
// EditText[] array = { txt1, txt2 };
// is the short version of
EditText[] array = new EditText[2];
array[0] = txt1;
array[1] = txt2;
showtxt.setTag(array);
showtxt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText[] array = (EditText[]) v.getTag();
String aaa = array[0].getText().toString();
String bbb = array[1].getText().toString();
Log.v("Example", aaa + " " + bbb);
}
});
} while(some condition)这可能并不理想,但是如果没有进一步的上下文,我无法猜测您的最终目标。希望这能有所帮助!
上一条建议
如果我们称Button和两个EditTexts为一行,您可以将每行存储在一个ViewGroup或它自己的视图中。假设您希望每行都有背景颜色:
View row = new View(this); // or this could be another LinearLayout
row.setBackgroundColor(0x0000ff);
// Create and add the Button and EditTexts to row, as in row.addView(showtxt), etc
...
linearLayout.addView(row);
showtxt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
View row = v.getParent()
String aaa = ((EditText) row.getChildAt(1)).getText().toString();
String bbb = ((EditText) row.getChildAt(2)).getText().toString();
Log.v("Example", aaa + " " + bbb);
}
});https://stackoverflow.com/questions/11173453
复制相似问题