简体   繁体   中英

Change text in TextView

I have a TextView element in my "activity_main.xml":

        <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="@string/my_best_text"
        android:background="#FF0000"
        />

and want to change the text inside this TextView with the id "text1"! I have tried in my "MainActivity.java" something like this:

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        ((TextView)findViewById(R.id.text1)).setText("Menu item selected -> " + position);
    }

How to do that correctly?

EDIT

My App crashed with these two lines

TextView txtView= ((TextView)findViewById(R.id.text1));
txtView.setText("Menu item selected -> " + position);

If you want to change the text at another point in your program, you can use setText

For your text that you provided, you want to change it to something like this:

@Override
public void onNavigationDrawerItemSelected(int position) {
    TextView txtView= ((TextView)findViewById(R.id.text1));
    txtView.setText("Menu item selected -> " + position);
}

Also, I would advise putting this line: TextView txtView= ((TextView)findViewById(R.id.text1)); in your onCreate for your intent if you have one, and then use the second line: txtView.setText("Menu item selected -> " + position); in your onNavigationDrawerItemSelected or anywhere else you need it.

Try this way:

final TextView textview= (TextView) findViewById(R.id.text1);
textview.setText("Menu item selected -> " + position);

There are many ways to do this, the common way is:

@Override
public void onNavigationDrawerItemSelected(int position) {

    TextView textView1 = (TextView) findViewById(R.id.text1);
    textView1.setText("Menu item selected -> " + position);
}

THis will work You can change your java code to :

@Override
public void onNavigationDrawerItemSelected(int position) {

    TextView text = (TextView) findViewById(R.id.text1); 
    text.setText("Menu item selected -> " + position);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM