Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ? 

 }
}

Any help is appreciated.

like image 990
George Avatar asked Sep 09 '10 09:09

George


2 Answers

You could try this:

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

the usage depends on your layout. Its possible, that the parent of your button is not the parent of your textview so be careful...

like image 61
WarrenFaith Avatar answered Oct 25 '22 15:10

WarrenFaith


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

I need to set visible an element from the same parent so I used this code :) and it worked

like image 25
David Avatar answered Oct 25 '22 14:10

David