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;
}