Reputation: 1095
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);
Upvotes: 0
Views: 83
Reputation: 1
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);
}
Upvotes: 0
Reputation: 1221
Try this way:
final TextView textview= (TextView) findViewById(R.id.text1);
textview.setText("Menu item selected -> " + position);
Upvotes: 0
Reputation: 1125
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);
}
Upvotes: 0
Reputation: 1248
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.
Upvotes: 1