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

后端 未结 3 1964
悲&欢浪女
悲&欢浪女 2021-02-12 17:32

This is going to be a bit lame question. I have the following code:

..............
 public void onCreate (Bundle bundle)
 {
  super.onCreate(bundle);
  this.setC         


        
相关标签:
3条回答
  • 2021-02-12 18:11
    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

    0 讨论(0)
  • 2021-02-12 18:27

    EDIT I dont think it will be possible. The view V only has the buttons view in it....

    You will know if you typecast the same

      class ButtonListener implements android.view.View.OnClickListener
        {
    
         public void onClick(View v) 
         {
    
            Button vg=(Button)v;
            Log.e("", "views are "+vg.getText());
    

    //However u can set the test here for ue textview txt.setText("change text");

         }
        }
    

    I did not understand your question properly. But if you just want to get the text out from ur TextView you can try like this

    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());
    
     }
    }
    
    0 讨论(0)
  • 2021-02-12 18:28

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

    0 讨论(0)
提交回复
热议问题