Android: TextView ignores Gravity and Margin

Ask by : Prexx November 03, 2012 17:28

Here is my code:

 //define tablerows. each table row has max 3 buttons
 LinearLayout llRow1 = (LinearLayout)findViewById(; llRow1.removeAllViews();

   float scale = getResources().getDisplayMetrics().density;
   int padding_5dp = (int) (5 * scale + 0.5f);

//Define FrameLayout
       FrameLayout flTmp = new FrameLayout(this);
       LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.FILL_PARENT, 1f);
       lp.setMargins(0, 0, padding_5dp, padding_5dp);

//Add dynamically TextView
TextView tvTmp = new TextView(this);
LinearLayout.LayoutParams tvPara=new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT );
tvPara.gravity = Gravity.BOTTOM | Gravity.LEFT;
tvPara.setMargins(padding_5dp, 0, 0, 0);

//Add dynamically Buttons for juice
    ImageButton btnTmp = new ImageButton(this);


//Add Button and TextView to FrameLayout


What i try to do is create an imagebutton dynamically with a textview description like following xml code:

<ImageButton android:background="@null" android:id="@+id/button_x" android:layout_width="fill_parent" android:layout_height="fill_parent" android:scaleType="fitXY" android:src="@drawable/button_graphic"></ImageButton>    
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:clickable="false" android:text="TEST TEST"></TextView>

works fine with my code, but the textview ignores margin and gravity parameters. its located on upper left corner without margins.

Any hint?

View original question

Answer by : DeeVNovember 03, 2012 17:28

The LayoutParams you use need to be of the type of parent that the child is contained in. You're FrameLayout contains the TextView, but you're assigning a LinearLayout.LayoutParams reference to it. Make it a FrameLayout.LayoutParams or change to a LinearLayout. If I had to guess, it's silently catching this error and just ignoring it.

View original answer