简体   繁体   English

更改TextView中的文本

[英]Change text in TextView

I have a TextView element in my "activity_main.xml": 我的“ activity_main.xml”中有一个TextView元素:

        <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"! 并想要更改此TextView中的ID为“ text1”的文本! I have tried in my "MainActivity.java" something like this: 我已经在我的“ MainActivity.java”中尝试了以下操作:

    @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 如果要在程序的另一点更改文本,可以使用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)); 另外,我建议将这一行放在下面: 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); onCreate ,如果有意图,则使用第二行: txtView.setText("Menu item selected -> " + position); in your onNavigationDrawerItemSelected or anywhere else you need it. 在您的onNavigationDrawerItemSelected或您需要的其他任何位置。

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 : 这将起作用您可以将Java代码更改为:

@Override
public void onNavigationDrawerItemSelected(int position) {

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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