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

后端 未结 2 437
名媛妹妹
名媛妹妹 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: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");
        }
    

提交回复
热议问题