Android:TextView忽略重力和边距

时间:2012-11-03 17:17:42

标签: android textview margin gravity

这是我的代码:

 //define tablerows. each table row has max 3 buttons
 LinearLayout llRow1 = (LinearLayout)findViewById(R.id.llRow1); 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);
       flTmp.setLayoutParams(lp);

//Add dynamically TextView
TextView tvTmp = new TextView(this);
tvTmp.setText("Test");
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);
tvTmp.setLayoutParams(tvPara);

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

[...]

//Add Button and TextView to FrameLayout
    flTmp.addView(btnTmp);
    flTmp.addView(tvTmp);

llRow1.addView(flTmp);

我尝试做的是使用textview描述动态创建一个图像按钮,如下面的xml代码:

<FrameLayout>
<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>
</FrameLayout>

可以正常使用我的代码,但textview会忽略边距和重力参数。 它位于左上角,没有边缘。

任何提示?

1 个答案:

答案 0 :(得分:3)

您使用的LayoutParams必须属于包含该子项的父级类型。您FrameLayout包含TextView,但您指定的是LinearLayout.LayoutParams 1}}引用它。将其设为FrameLayout.LayoutParams或更改为LinearLayout。如果我不得不猜测,它会默默地捕捉到这个错误并忽略它。

相关问题