How do I declare a TextView variable so that I can use it anywhere?

后端 未结 2 412
名媛妹妹
名媛妹妹 2021-01-14 05:20

I have started coding in java/android just today so excuse me if I am being a total idiot here.

I have been facing this problem for the past hour, I have tried to go

相关标签:
2条回答
  • 2021-01-14 05:35

    You have to instantiate the variable after the setcontentView method was called, so you have to do the following:

    public class MainActivity extends Activity {
    
    TextView test;
    
    @Override
    onCreate(Bundle s){
        ...
        setContentView(R.layout.yourLayout);
        test = (TextView)findViewById(R.id.textView2);
    }
    
    
    public void registermessage(View view) {
    
        test.setText("Test");
    }
    
    0 讨论(0)
  • 2021-01-14 05:48

    Declare it as a variable of your activity and initialize it after calling setContentView(). There is no need to pass a View parameter in your function if you're just setting the text of your TextView.

    public class MainActivity extends Activity {
    
        private TextView test;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.layout_launch);
            test = (TextView)findViewById(R.id.textView2);
            registermessage();
        }
    
        public void registermessage() {    
            test.setText("Test");
        }
    
    0 讨论(0)
提交回复
热议问题