How to create new TextViews within a scrollview by Java in android studio?

0

Hi, I have a question for making an application: I need to create a new TextView inside a ScrollView with each click of a button. I need to also add attributes to the textview, such as positioning it on the screen, background color, and text color. I thought of doing so:

TextView texto = new TextView(this);

But, this way, it just creates the textview, I need to know how to change the attributes of the textView and how to put it in the scrollView. Can someone tell me how I do this?

    
asked by anonymous 21.09.2018 / 22:57

2 answers

0
  

I need to know how to change TextView attributes and how to put it in ScrollView

Let's say you have a ScrollView in your layout, and all ScrollView is ViewGroup , you would use the addView() method to place your TextView within the ScrollView. But we know that ScrollViews can only contain a child view , so we usually end up with this pattern:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/scroll_container"
        android:orientation="vertical">

    </LinearLayout>

</ScrollView>

where LinearLayout scroll_container is the only child view of ScrollView.

Now we will use this LinearLayout (which is a ViewGroup) to serve as the host for the TextViews we are going to add.

// Primeiro, iniciamos o container
LinearLayout container = findViewById(R.id.scroll_container);

// Criamos o TextView
TextView text = new TextView(this);

// Criamos os parâmetros do layout no qual
// este TextView será inserido
LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
textParams.topMargin = dpToPx(16);
textParams.bottomMargin = dpToPx(32);
text.setLayoutParams(textParams);

// Agora brincamos com o TextView
text.setGravity(Gravity.CENTER_HORIZONTAL);
text.setText("https://developer.android.com/reference/android/widget/TextView");
text.setTextColor(Color.parseColor("#ff9800")); // Laranja
text.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); // 16dp

// Finalmente adicionamos o text ao container
container.addView(text);

Here's the DP converter for Pixels, put it off the onCreate:

private int dpToPx(int dp) {
    int px = dp;
    try {
        px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    } catch (Exception ignored){}
    return px;
}
    
22.09.2018 / 16:22
0

About setting the attributes you want by code:

TextView txtView = new TextView(this);
txtView.setTextSize(12);
txtView.setText("hdfas");
txtView.setGravity(Gravity.RIGHT); 
    
21.09.2018 / 23:09