Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

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

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 google it but couldn't find any answers.

How do I declare a TextView as a static/variable so that I can access it simply by typing "variablename." anywhere in my code?

I am not trying to access the TextView from another activity, these are all in the same one.

This is what my code looks like(all in mainactivity.java) :

public class MainActivity extends Activity {

    TextView test = (TextView)findViewById(R.id.textView2);

    public void registermessage(View view) {
        test.setText("Test");
    }
}

This doesn't give any errors in Eclipse but will simply force close when I try to run it on my phone.

I can succeed when I move the line I declare test as a textview to the public void but I want to be able to use the variable test from any void in the activity.

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...