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.
TextView tv1 = (TextView)findViewById(R. id. textView1); tv1. setText("Hello"); setContentView(tv1);
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)
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
remove this.. setContentView(tv1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With