How to create new Textviews inside a Java scrollview in android studio?

Asked

Viewed 302 times

0

Hi, I have a question to make an app: I need to create a new Textview within a Scrollview at each click of a button. I still need to put attributes to the textview, such as its placement on the screen, background color, and text color. I thought to do so:

TextView texto = new TextView(this);

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

2 answers

0

About setting the attributes you want by code:

TextView txtView = new TextView(this);
txtView.setTextSize(12);
txtView.setText("hdfas");
txtView.setGravity(Gravity.RIGHT); 
  • thanks! need now to learn how to put it inside the scrollview... Anyway, thanks for the help!

0

And I need to know how to change Textview attributes and how to put in Scrollview

Let’s say you have a Scrollview in your layout, all of which ScrollView is a ViewGroup, you would use the method addView() to put your Textview inside Scrollview. But we know that Scrollviews can only contain a daughter view, then 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>

in which the Linearlayout scroll_container is the only view daughter of Scrollview.

Now we will use this Linearlayout (which is a Viewgroup) to host the Textviews that we will 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 is the DP to Pixels converter, put it out of 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;
}

Browser other questions tagged

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