Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change TextView text

Tags:

I'm trying to change my TextView text from the code.

This is what my xml looks like:

XML: <TextView     android:id="@+id/textView1"     android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:gravity="center_vertical|center_horizontal" /> 

And the code:

TextView tv1 = (TextView)findViewById(R.id.textView1); tv1.setText("Hello"); setContentView(tv1); 

I'm getting an error on my device and the application stops. I tried to show a TextView (not connected to an XML TextView) and it worked.

like image 478
Imri Persiado Avatar asked Nov 19 '12 11:11

Imri Persiado


People also ask

Can we change the text in TextView?

TextView tv1 = (TextView)findViewById(R. id. textView1); tv1. setText("Hello"); setContentView(tv1);

How do I change TextView text in Kotlin?

We can get and modify the content of edit text defined in the XML layout in Kotlin class file as: val editText = findViewById<EditText>(R. id. editText_id)


2 Answers

Your approach is incorrect. I think it will be Null Pointer Exception (next time post log cat)

You need to specify the layout you are using first, before finding views.

Java:

// Specify the layout you are using. setContentView(R.layout.yourlayout);  // Load and use views afterwards TextView tv1 = (TextView)findViewById(R.id.textView1); tv1.setText("Hello"); 

Kotlin:

// Specify the layout you are using. setContentView(R.layout.yourlayout)  // Load and use views afterwards val tv1: TextView = findViewById(R.id.textView1) tv1.text = "Hello" 

Click Here to study exactly you want to know

like image 170
Abhi Avatar answered Oct 20 '22 23:10

Abhi


remove this.. setContentView(tv1);

like image 23
Henrik Avatar answered Oct 21 '22 01:10

Henrik