How to Add a TextView to LinearLayout in Android
In Android programming, occasionally you need to add views to a pre-defined XML layout dynamically in your code. This can be achieved by following a systematic approach.
Let's say you have an XML layout with a LinearLayout with an ID "info":
<code class="xml"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:id="@+id/info" android:layout_height="wrap_content" android:orientation="vertical" > </LinearLayout></code>
To add a TextView to this LinearLayout in code:
Get the LinearLayout view from your XML layout:
<code class="java">View linearLayout = findViewById(R.id.info);</code>
Create a TextView programmatically:
<code class="java">TextView valueTV = new TextView(this);</code>
Configure the TextView:
<code class="java">valueTV.setText("hallo hallo"); valueTV.setId(5);</code>
Set the TextView layout parameters:
<code class="java">valueTV.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));</code>
Add the TextView to the LinearLayout:
<code class="java">((LinearLayout) linearLayout).addView(valueTV);</code>
Note: Make sure to use LinearLayout.LayoutParams for the TextView's layout parameters and cast the linearLayout view to LinearLayout before adding the valueTV TextView to it.
The above is the detailed content of How to Programmatically Add a TextView to a LinearLayout in Android?. For more information, please follow other related articles on the PHP Chinese website!