开发者

Setting text in activity using Button

开发者 https://www.devze.com 2023-01-25 15:00 出处:网络
I was wondering what is the correct way to set the text of a TextView after a button has been pushed? I currently have an app that would change the text every time the activity was created (but for no

I was wondering what is the correct way to set the text of a TextView after a button has been pushed? I currently have an app that would change the text every time the activity was created (but for now it on开发者_开发问答ly sets the text as one value for testing purposes):

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mama);
    TextView joke = (TextView) findViewById(R.id.TextView02);
    joke.setText("This is a test");
    Button nextButton = (Button) findViewById(R.id.Button01);
    nextButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(JokesMamaActivity.this, JokesMamaActivity.class));
            finish();
        }
    });
}

How would I be able to set the text without creating a new activity, and have the ability to continually change the text after the button has been clicked?


Short answer:

...
public void onClick(View v) {
    TextView joke = (TextView) findViewById(R.id.TextView02);
    joke.setText("Text after click");
}
...

Of course, there is no real need to search for joke TextView again, you can make it final after first find().

0

精彩评论

暂无评论...
验证码 换一张
取 消