2

关于动态设置按钮的位置有很多问题,但我只想将按钮的位置更改为屏幕中心。我的布局是RelativeLayout。

更新:

一开始,myButton 在 XML 中的位置设置为:

<Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="Menu" />

任何建议将不胜感激

4

5 回答 5

4

请参见下面的示例(单击按钮,它将移动到中心)。

活动主.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/my_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="Menu" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {
    private View mView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mView = findViewById(R.id.my_view);
        mView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewGroup.LayoutParams vg_lp = mView.getLayoutParams();

                // Make sure we are in RelativeLayout
                if (vg_lp instanceof RelativeLayout.LayoutParams) {
                    RelativeLayout.LayoutParams rl_lp = new RelativeLayout.LayoutParams(vg_lp);
                    rl_lp.addRule(RelativeLayout.CENTER_IN_PARENT);
                    mView.setLayoutParams(rl_lp);
                }
            }
        });
    }
}
于 2012-07-31T12:28:49.083 回答
0

尝试:

      ......
      RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) button.getLayoutParams();
      layoutParams.leftMargin = parentLayout.getWidth()/2;
      layoutParams.topMargin = parentLayout.getHeight()/2;
      button.setLayoutParams(layoutParams);
      ...... 
于 2012-07-31T12:08:55.100 回答
0

试试这个:

   RelativeLayout RL = (RelativeLayout)findViewById(R.id.relative_layout);
   RL.gravity(Gravity.CENTER);

这样,RL 的所有子视图都将居中;

   Button anyButton = new Button(this);
   RL.addSubview(anyButton);//this genereted button will be in center as well
于 2012-07-31T12:09:40.477 回答
0

将此 2 行添加到要在 xml 文件中居中的组件:

android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
于 2012-07-31T12:10:09.190 回答
0

试试这个,

RelativeLayout my_layout = new RelativeLayout(this);
my_layout.setId(some_value);
Button my_btn = new Button(this);
RelativeLayout.LayoutParams my_params = new RelativeLayout.LayoutParams(btn_height,btn_width);
my_params.addRule(RelativeLayout.CENTER_IN_PARENT,my_layout.getId());
my_layout.addView(my_btn,my_params);
于 2012-07-31T12:12:34.480 回答