Android :: findViewByID – ¿cómo puedo obtener la vista de un TextView a través de un Listener de otro elemento de IU?
Esto va a ser una pregunta poco cojo. Tengo el siguiente código:
.............. 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 ? } }
Cualquier ayuda es apreciada.
Usted podría intentar esto:
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(...); } } }
el uso depende de su diseño. Es posible, que el padre de su botón no es el padre de su texto, así que tenga cuidado …
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(...); } } }
Necesito fijar un elemento visible del mismo padre así que utilicé este código 🙂 y trabajó
EDIT No creo que será posible. La vista V sólo tiene la vista de los botones en ella ….
Usted sabrá si usted typecast el mismo
class ButtonListener implements android.view.View.OnClickListener { public void onClick(View v) { Button vg=(Button)v; Log.e("", "views are "+vg.getText());
// Sin embargo u puede establecer la prueba aquí para ue textview txt.setText ("change text");
} }
No he entendido bien su pregunta. Pero si sólo desea obtener el texto de ur TextView puede intentar de esta manera
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()); } }