Home > Java > javaTutorial > body text

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

Susan Sarandon
Release: 2024-10-27 01:40:03
Original
299 people have browsed it

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>
Copy after login

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>
    Copy after login
  2. Create a TextView programmatically:

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

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

    <code class="java">valueTV.setLayoutParams(new LayoutParams(
    LayoutParams.FILL_PARENT,
    LayoutParams.WRAP_CONTENT));</code>
    Copy after login
  5. Add the TextView to the LinearLayout:

    <code class="java">((LinearLayout) linearLayout).addView(valueTV);</code>
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!