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;
}
thanks! need now to learn how to put it inside the scrollview... Anyway, thanks for the help!
– Omeuestilo