动态添加元素的setOnClickListener范围

时间:2012-06-23 22:23:08

标签: android event-listener

我正在以编程方式和动态添加一些元素(按钮和文本视图)与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)

我几乎是新手。如何在点击回调函数中访问txt1和txt2?

1 个答案:

答案 0 :(得分:1)

您需要定义变量,它们将具有类范围的范围:

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功能将能够看到txt1txt2

另外

由于您似乎在一个LinearLayout中创建了大量txt1txt2,因此您可以将Button的引用传递给其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中。假设您希望每行都有背景颜色:

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);
    }
});