In my application, I want to set top and bottom margin of 8 dip to a textview. So if I do it like -
<TextView
android:id="@+id/tv_text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/settings_plain_text"/>
it works fine where the style contents are -
<style name="settings_plain_text">
<item name="android:layout_marginTop"> 8dip </item>
<item name="android:layout_marginBottom"> 8dip </item>
<item name="android:textSize"> 18sp </item>
</style>
But when I apply the same style to that textview programmatically like -
textview.setTextAppearance(context, R.style.settings_plain_text);
it does not show the top and bottom margin that I've set in style. Please help.
TextView tv1 = new TextView(this); tv1. setPadding(5, 0, 5, 0); tv1. setLayoutParams(new LayoutParams(LayoutParams.
margin); int marginTopPx = (int) (marginTopDp * getResources(). getDisplayMetrics(). density + 0.5f); layoutParams. setMargins(0, marginTopPx, 0, 0); recyclerView.
More simplified version of answered by Gianluca P.
public void applyTextStyle(TextView v, int styleResId)
{
int[] attrs= new int[] {
android.R.attr.layout_marginTop, // 0
android.R.attr.layout_marginLeft, // 1
android.R.attr.layout_marginBottom, // 2
android.R.attr.layout_marginRight}; // 3 (used in example)
final TypedArray arr = this.obtainStyledAttributes(styleResId,attrs);
try {
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
lp.topMargin = arr.getDimensionPixelSize(0,lp.topMargin);
lp.leftMargin = arr.getDimensionPixelSize(1,lp.leftMargin);
lp.bottomMargin = arr.getDimensionPixelSize(2,lp.bottomMargin);
lp.rightMargin = arr.getDimensionPixelSize(3,lp.rightMargin);
v.requestLayout();
} finally {
arr.recycle();
}
}
setTextAppearence(..)
only setups xml attributes with the prefix android:text_*
but you can still write you own method that reads other attributes and sets them programmatically knowing the underlying LayoutParams
implementation.
Please mind that you can use a ContextThemeWrapper
for obtaining specific theme values or pass a syle resource id in .obtainStyledAttributes(..
)
As an example:
int[] attrs= new int[] {
android.R.attr.layout_marginTop, // 0
android.R.attr.layout_marginLeft, // 1
android.R.attr.layout_marginRight, // 2 (used in example)
android.R.attr.layout_marginBottom}; // 3
final TypedArray arr = context.obtainStyledAttributes(attrs);
try {
// ...
layoutParams.rightMargin = arr.getDimensionPixelSize(2);
// ...
} finally {
arr.recycle();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With