Várias Textview

Asked

Viewed 103 times

0

I was wondering if there’s any way I can add a Textview to a layout in java. type I have an xml that has a Textview and in class Activity I use setContentView() to link the two, but I wanted to put more Textview in Layout by Java and not by xml

1 answer

2


To do this simply create an object of the type Textview.

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

TextView textView = new TextView(this);

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

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

Done. We created our Textview through Java. Now we just need to use the method addView of your XML main view.

Sample 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 Textview, simply wrap the sample code within one for

  • esta dando erro nesse codigo ViewGroup viewGroup = findViewById(R.id.container); e se eu colocar ViewGroup viewGroup = (ViewGroup)findViewById(R.id.container); da erro na hora de add a View

  • @Francianderson What error? you are putting the correct ID (like in the XML example) ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.