在代码中设置TextView的边距和重力不起作用。

7
如果我只为我的线性布局中的文本视图设置了margin,一切都正常。 如果我只为我的文本视图设置了gravity,它也可以工作。但是如果我同时设置这两个属性(gravity和margins),那么gravity会保持在左边,并且成功设置了margins。
以下是设置两个属性时不符合预期的代码:
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文件。
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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接