1

I create a TableLayout dynamically via code and want to set a margin between columns. The only type of content my TableRows contain are TextViews.

My intention was to put a simple android:layout_marginRight on each TextView. But I want to definde this via xml instead of code.

What I tried:

The code:

txtView.setTextAppearance(context, R.style.TableTextView);
txtView.setText(content);
tableRow.addView(txtView);

The XML

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="TableTextView">
      <item name="android:textAppearance">?android:attr/textAppearanceLarge</item>
      <item name="android:textStyle">bold</item>
      <item name="android:layout_marginRight">5dip</item>
  </style>
</resources>

What happens:

The layout_marginRight set in the XML does not work, but the textAppearance and textStyle set in the XML do work. I assume the setTextAppearance-method is the wrong way for assigning a margin to a TextView? It would be really nice if I could do this via XML (like I tried it above) instead of Java-code.

Thank you!

alapeno
  • 2,724
  • 6
  • 36
  • 53

2 Answers2

1

This happens because you're setting the style to the text itself and not the TextView element. You should set the element style in the XML. it's possible to achive this from the code as well, but i think it's best to do that in the XML Layout file.

Something like :

<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    style="@style/mTableTextView" /> 

About setting that from code, i'm not an expert but i understood you can inflate it somehow. Check out This, And This questions.

Community
  • 1
  • 1
eric.itzhak
  • 15,752
  • 26
  • 89
  • 142
  • Thx, looks nice but how can I apply that to my dynamically generated TextView objects? The thing is that I need to create the TextViews itself in Java instead of XML because the amount of TextViews in my table is not static and can differ from time to time. – alapeno May 29 '12 at 10:56
  • You can inflate it , i'm not an experet but revised answer with links – eric.itzhak May 29 '12 at 11:34
1

You want to give margin between columns

android.widget.TableRow.LayoutParams param = new android.widget.TableRow.LayoutParams();
param.rightMargin = Converter.dpToPixel(10, getContext()); // right-margin = 10dp
button.setLayoutParams(param);

// Converter:
private static Float scale;
public static int dpToPixel(int dp, Context context) {
    if (scale == null)
        scale = context.getResources().getDisplayMetrics().density;
    return (int) ((float) dp * scale);
}

you can set different of value table parameters.

MobileEvangelist
  • 2,583
  • 1
  • 25
  • 36