我有一个LinearLayout
包含一些Button
个,我将onCreate(..)
方法中的setContentView(R.layout.myscreen)
方法添加到我的活动中。到目前为止没有惊喜。
如何获得对这些按钮的迭代器的引用?我想向他们添加听众,但我不想使用他们的android:id
直接引用Button。
答案 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.
这可能有用。 然后,您可以将这些视图与其内置方法一起使用,以执行所需的工作量。