Android::findViewByID - 如何通过另一个 UI 元素的监听器获取 TextView 的 View ?

标签 android

这将是一个有点蹩脚的问题。我有以下代码:

..............
 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/

相关文章:

java - SharedPreferences 默认模式

android shell内容查询错误

java - 打开应用程序前的锁屏服务

android - 当应用程序进入后台时如何检测以前的 Activity

android - 通过xml设置自定义字体

android - Activity 作为应用程序安装

android - 在保持 android :targetSdkVersion to be 14 的同时在 ICS 上显示菜单按钮

java - 使带下划线的文本拉伸(stretch) 100%

Android studio 的模拟器没有启动

java - Prolog中不允许Android Studio Project内容