获取对我的 Android Activity 中的视图的引用
我有一个由几个 Button
组成的 LinearLayout
,我使用 将其添加到
。到目前为止没有什么意外。onCreate(..)
方法中的活动中setContentView(R.layout.myscreen)
如何获取这些按钮的迭代器的引用?我想向它们添加侦听器,但我不想使用其 android:id
直接引用按钮。
I have a LinearLayout
comprising of a few Button
s and I add this to my activity in the onCreate(..)
method with setContentView(R.layout.myscreen)
. No surprises so far.
How do I get a reference to an iterator to these buttons? I'd like to add listeners to them but I'd rather not directly reference the Button's using their android:id
.
Similar questions have been asked here and here but they don't quite answer my question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试类似的方法,在 xml 中向 LinearLayout 提供一个 id root_layout
其中 mLayout 是线性布局的对象,并且您的活动必须实现
OnClickListener
,这里是通用侦听器注意:为此正常工作,线性布局必须只包含按钮,没有其他视图
Try something like this provide an id root_layout in xml to LinearLayout
Where mLayout is object of you Linear Layout and Your activity must implements
OnClickListener
and here goes general listenerNOTE: For this to work properly you Linear Layout must only contains button no other views
您应该看看我的答案这里< /a>.
简而言之。我将通过在每个
Button
的 XML 布局中设置onClick
属性来为按钮分配一个侦听器。在您的
Activity
内部,您需要一个像下面这样的公共方法,这基本上就是您想要在侦听器中执行的操作。You should take a look at my answer here.
In short. I'd assign the buttons a listener by setting the
onClick
attribute in the XML layout on eachButton
.Inside of your
Activity
you'll need a public method like the one below which basically is what you want to do in your listener.如果您想访问其他元素,您可以尝试以下语法:
例如:
TextView textView= (TextView) findViewById(R.id.t1); //我使用 t1 在布局中引用我的文本视图。
这可能有效。
然后,您可以使用这些视图及其内置方法来执行任意数量的工作。
If you want to go for accessing other elements you may try following syntax:
<ElementClass> <referencevariable> = (<ElementClass>) findViewById(R.id.<id_of_the_element>);
For Example:
TextView textView= (TextView) findViewById(R.id.t1); //I used t1 to refer my textview in the Layout.
This might work.
Then you can use these views with their inbuilt methods to perform as many as work you want.