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

Dix*_*ine 7 layout android margin gravity

如果我只为我的textview设置边距,那就是线性布局,一切正常.如果我只为我的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);
Run Code Online (Sandbox Code Playgroud)

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

kco*_*ock 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);
Run Code Online (Sandbox Code Playgroud)