这将是一个有点蹩脚的问题。我有以下代码:
..............
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 的父级,所以要小心...
关于Android::findViewByID - 如何通过另一个 UI 元素的监听器获取 TextView 的 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3675238/