Android :: findViewByID-如何通过另一个UI元素的侦听器获取TextView的视图? [英] Android::findViewByID - how can I get View of a TextView through a Listener of another UI element?
本文介绍了Android :: findViewByID-如何通过另一个UI元素的侦听器获取TextView的视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这将是一个la脚的问题.我有以下代码:
This is going to be a bit lame question. I have the following code:
..............
public void onCreate (Bundle bundle)
{
super.onCreate(bundle);
this.setContentView(R.layout.main2);
Button bnt = (Button) this.findViewById(R.id.browser);
bnt.setOnClickListener(new ButtonListener());
}
..............
class ButtonListener implements android.view.View.OnClickListener
{
public void onClick(View v)
{
// I have a TextView in my xml layout file.
// I'd like to get it and change my text when I click this button.
// But I can't get it (the TextView) unless I make it as a value of a static member of this class and pass it to the constructor.
//I believe I am missing a big point here, so i'd be very thankful if you could explain how this is meant to be done ?
}
}
感谢您的帮助.
推荐答案
您可以尝试以下方法:
class ButtonListener implements android.view.View.OnClickListener {
public void onClick(View v) {
View parent = (View)v.getParent();
if (parent != null) {
TextView txtView = parent.findViewById(R.id.mytextview);
txtView.setText(...);
}
}
}
用法取决于您的布局.可能是按钮的父级不是textview的父级,所以请注意...
the usage depends on your layout. Its possible, that the parent of your button is not the parent of your textview so be careful...
这篇关于Android :: findViewByID-如何通过另一个UI元素的侦听器获取TextView的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文