Set margin in style and apply that style to TextView programmatically

Rajkiran picture Rajkiran · Feb 28, 2012 · Viewed 12.8k times · Source

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.

Answer

Gianluca P. picture Gianluca P. · Jan 7, 2016

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