繁体   English   中英

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

[英]Android::findViewByID - how can I get View of a TextView through a Listener of another UI element?

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

..............
 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的父级,所以要小心......

class ButtonListener implements android.view.View.OnClickListener {
    public void onClick(View v) {
       View p = (View) view.getRootView();        
        if (p != null) {
            TextView txtView = (TextView) p.findViewById(R.id.mytextview);
            txtView.setText(...);
        }
    }
}

我需要设置一个来自同一个父元素的元素,所以我使用了这个代码:)并且它有效

编辑我不认为这是可能的。 视图V中只有按钮视图....

你会知道你是否相同

  class ButtonListener implements android.view.View.OnClickListener
    {

     public void onClick(View v) 
     {

        Button vg=(Button)v;
        Log.e("", "views are "+vg.getText());

//但是你可以在这里为ue textview txt.setText设置测试(“改变文本”);

     }
    }

我没有正确理解你的问题。 但是,如果你只想从你的TextView中获取文本,你可以尝试这样

TextView txt;

public void onCreate (Bundle bundle)
 {
  super.onCreate(bundle);
  this.setContentView(R.layout.main2);
  Button bnt = (Button) this.findViewById(R.id.browser);
  txt=(TextView)this.findViewById(R.id.urtextview);
  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 ? 
//I think this should get u the string...
System.out.println("text is "+txt.getText().toString());

 }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM