Home  >  Article  >  Java  >  How to Programmatically Add a TextView to a LinearLayout in Android?

How to Programmatically Add a TextView to a LinearLayout in Android?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 01:40:03299browse

How to Programmatically Add a TextView to a LinearLayout in Android?

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:

  1. Get the LinearLayout view from your XML layout:

    <code class="java">View linearLayout =  findViewById(R.id.info);</code>
  2. Create a TextView programmatically:

    <code class="java">TextView valueTV = new TextView(this);</code>
  3. Configure the TextView:

    <code class="java">valueTV.setText("hallo hallo");
    valueTV.setId(5);</code>
  4. Set the TextView layout parameters:

    <code class="java">valueTV.setLayoutParams(new LayoutParams(
    LayoutParams.FILL_PARENT,
    LayoutParams.WRAP_CONTENT));</code>
  5. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn