如何通过代码设置组件的顶部中心位置?

时间:2014-04-11 10:46:16

标签: java android

我需要通过java代码生成用户视图,我无法设置TextView的位置。我想在LinearLayout之上设置组件并将其居中,如果我使用xml,它会是这样的:

 <TextView
    android:layout_gravity="center"/>

我的代码是:

LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
test = new TextView(this);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
test.append("test");
activityTitle.setGravity(Gravity.CENTER);
layout.addView(activityTitle, params);
setContentView(layout);

这是输出:

  

enter image description here

3 个答案:

答案 0 :(得分:1)

试试这个..

layout.setGravity(Gravity.CENTER|Gravity.TOP);用于LinearLayout

LinearLayout layout = new LinearLayout(this);
layout.setGravity(Gravity.CENTER|Gravity.TOP);
layout.setOrientation(LinearLayout.VERTICAL);
test = new TextView(this);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
test.append("test");
activityTitle.setGravity(Gravity.CENTER);
layout.addView(activityTitle, params);
setContentView(layout);

答案 1 :(得分:0)

或者

LinearLayout linearLayoutstate = new LinearLayout(this);

  linearLayoutstate.setOrientation(LinearLayout.HORIZONTAL);
  linearLayoutstate.setGravity(Gravity.CENTER_HORIZONTAL);
  LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);

  TextView stateTitletv = new TextView(this);

  stateTitletv.setText("test");

  linearLayoutstate.addView(stateTitletv);

  linearLayoutstate.addView(state_valuetv);

  LL_SelectedFilters.addView(linearLayoutstate,layoutParams);

答案 2 :(得分:0)

将TextView的宽度更改为MATCH_PARENT

LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);