findViewById() not working in a not MainActivity class

后端 未结 4 1443
耶瑟儿~
耶瑟儿~ 2020-12-13 18:46

I have a text view in my Lyout and I would like to set some text to this textview. This should be made in a class which is not a MainActivity class.

The problem is t

相关标签:
4条回答
  • 2020-12-13 19:16
    findViewById(R.id.EmailTextView);
    

    You either

    1. Didn't set the View layout
    2. Have no View with ID EmailTextView, and thus findViewById returns null. You don't have to put the type, but the ID you've given him in the XML.

    EDIT: definitely the 1 based on your new comments.

    0 讨论(0)
  • 2020-12-13 19:18

    When you call findViewById matters. The layout must have already happened. You must already have set a content view, etc.

    There are ways to work around this, as shown in other answers, but they work fundamentally differently from findViewById, and should only be used as a substitute if you understand exactly how they work. Most often it's far more efficient to just wait until after the initial layout has already occurred.

    0 讨论(0)
  • 2020-12-13 19:20

    Calling findViewById() on the Activity object will only work if the current Activity layout is set by setContentView. If you add a layout through some other means, then you need the View object of the layout and call findViewById() on it.

    View v = inflater.inflate(id_number_of_layout); # such as R.layout.activity_main
    View innerView = v.findViewById(id_number_of_view_inside_v);
    

    If the layout is supposed to be the main layout of the activity, then do this:

    public class MyActivity extends Activity{
      TextView emailTextView; 
    
      @Override
      public void onCreate(Bundle savedInstanceState){
         super.onCreate(savedInstanceState);
         setContentView(id_number_of_layout);
         emailTextView = (TextView) findViewById(R.id.EmailTextView);
         // ... whatever other set up you need to do ...
      }
    
      public void getUserInformation() {
         // .... regular code ... 
      }
    }
    
    0 讨论(0)
  • 2020-12-13 19:26

    You have not set the content View yet?


    to do this use something like this:

    public class MainActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
    
        }
    
    
    }
    
    0 讨论(0)
提交回复
热议问题