7

如果我只为我的文本视图设置边距,即在线性布局内,一切正常。如果我只为我的 textview 设置重力,它就可以工作。但是,如果我同时设置了两个属性(重力和边距),重力保持在左边,边距设置成功。

我设置两个属性的代码不能按预期工作:

tv2=new TextView(this);
tv2.setText("Text");
LinearLayout.LayoutParams para=new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT );
para.setMargins(0, 10, 0, 10); //left,top,right, bottom
tv2.setLayoutParams(para);
tv2.setGravity(android.view.Gravity.CENTER_HORIZONTAL);

我必须在代码中构建我的布局,不能使用 xml 文件。

4

1 回答 1

14

尝试改用这个:

para.gravity = Gravity.CENTER_HORIZONTAL;
tv2.setLayoutParams(para);

//the below sets the view's content gravity, not the gravity
//of the view itself. Since the width is wrap_content, this
//has no effect.
//tv2.setGravity(android.view.Gravity.CENTER_HORIZONTAL);
于 2011-01-27T16:50:49.513 回答