在我的Android Activity中获取对Views的引用

时间:2011-02-28 11:47:05

标签: android button view iterator

我有一个LinearLayout包含一些Button个,我将onCreate(..)方法中的setContentView(R.layout.myscreen)方法添加到我的活动中。到目前为止没有惊喜。

如何获得对这些按钮的迭代器的引用?我想向他们添加听众,但我不想使用他们的android:id直接引用Button。

类似的问题已经被问到herehere,但它们并没有完全回答我的问题。

3 个答案:

答案 0 :(得分:6)

尝试类似这样的事情,在xml中提供一个id root_layout到LinearLayout

LinearLayout mLayout = (LinearLayout) findViewById(R.id.root_layout);
    for(int i = 0; i < mLayout.getChildCount(); i++)
    {
        Button mButton = (Button) mLayout.getChildAt(i);
        mButton.setOnClickListener(this);
    }

其中mLayout是你的对象线性布局和你的活动必须实现OnClickListener,这里是普通的监听器

@Override
public void onClick(View v)
{
    Button mButton = (Button)v;
    String buttonText = mButton.getText().toString();

}

注意:为了使其正常工作,线性布局必须只包含按钮,没有其他视图

答案 1 :(得分:4)

你应该看看我的回答here

简而言之。我通过在每个onClick的XML布局中设置Button属性来为按钮分配监听器。

Activity内,您需要一个像下面那样的公共方法,基本上就是您想要在听众中做的事情。

public void myFancyMethod(View v) {
    // do something interesting here
}

答案 2 :(得分:0)

如果您想访问其他元素,可以尝试使用以下语法:

<ElementClass> <referencevariable> = (<ElementClass>) findViewById(R.id.<id_of_the_element>);

例如:

TextView textView= (TextView) findViewById(R.id.t1); //I used t1 to refer my textview in the Layout.

这可能有用。 然后,您可以将这些视图与其内置方法一起使用,以执行所需的工作量。