Android :: findViewByID - как я могу получить представление TextView через прослушиватель другого элемента пользовательского интерфейса? - PullRequest
18 голосов
/ 09 сентября 2010

Это будет немного неубедительный вопрос.У меня есть следующий код:

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

 }
}

Любая помощь приветствуется.

Ответы [ 3 ]

26 голосов
/ 09 сентября 2010

Вы можете попробовать это:

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(...);
        }
    }
}

использование зависит от вашего макета.Возможно, родитель вашей кнопки не является родителем вашего текстового представления, поэтому будьте осторожны ...

7 голосов
/ 11 декабря 2010
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(...);
        }
    }
}

Мне нужно установить видимый элемент от того же родителя, чтобы я использовал этот код :), и он работал

0 голосов
/ 09 сентября 2010

РЕДАКТИРОВАТЬ Я не думаю, что это будет возможно.Представление V имеет только представление кнопок в нем ....

Вы узнаете, если вы вводите то же самое

  class ButtonListener implements android.view.View.OnClickListener
    {

     public void onClick(View v) 
     {

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

// Однако вы можете установить здесь тест для текста 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());

 }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...