Multiple TextView

0

I would like to know if I have a TextView in a layout by java. I have an xml that has a TextView and in the Activity class I use the setContentView () to bind the two, but I wanted to put more TextView in the Layout by Java and not by xml

    
asked by anonymous 25.02.2018 / 03:05

1 answer

2

To do this simply create an object of type TextView .

When we create this object, we need to pass the parameter Context

TextView textView = new TextView(this);

Now you need to set the size of the element. For this we will use the method setLayoutParams and in it we will pass an object of type new LinearLayout.LayoutParams() .

textView.setLayoutParams( new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT, //Largura
        LinearLayout.LayoutParams.WRAP_CONTENT  //Altura
) );

Ready. We create our TextView through Java. Now we only need to use the addView method of the main View of your XML.

Example Code:

TextView textView = new TextView(this);
textView.setLayoutParams( new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT,
        LinearLayout.LayoutParams.WRAP_CONTENT
) );
textView.setText("Olá mundo");

ViewGroup container = findViewById(R.id.container);
container.addView( textView );

XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="br.com.valdeirsantana.stackoverflow.MainActivity"
    android:id="@+id/container">

</android.support.constraint.ConstraintLayout>

To create multiple TextViews, simply wrap the sample code inside a for

    
25.02.2018 / 03:21