Android 让按钮不在屏幕中央
Android getting Button not going in center of screen
我想在屏幕中央制作一个按钮:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="@color/black"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="0dp"
tools:context="com.vroy.trapper.MainMenuActivity">
<Button
android:id="@+id/playBtn"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/play_button_text"
android:background="@drawable/round_button"
/>
</RelativeLayout>
(我将 width/height 设置为 0dp,因为我以编程方式更改了它们。)
问题是在 XML 设计选项卡中,按钮似乎位于屏幕中央(如果我将 width/height 设置为 50dp 进行测试),而我实际上 运行 按钮出现在屏幕左上方的程序。
如何确保按钮实际位于屏幕中央?
这是我设置按钮 width/height 的代码:
int screenWidth = getResources().getDisplayMetrics().widthPixels;
// int screenHeight = getResources().getDisplayMetrics().heightPixels;
Button playBtn = (Button) findViewById(R.id.playBtn);
int playBtnWidth = screenWidth/3;
playBtn.setLayoutParams(new LayoutParams(playBtnWidth, playBtnWidth));
通过以编程方式设置 LayoutParams,您将这些参数中的所有信息重置为默认值(高度和宽度除外,因为您在构造函数中设置了它们)。尝试将 LayoutParams 创建为变量,然后设置布局位置。
LayoutParams params = new LayoutParams(playBtnWidth, playBtnWidth);
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
playBtn.setLayoutParams(params);
我想在屏幕中央制作一个按钮:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="@color/black"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="0dp"
tools:context="com.vroy.trapper.MainMenuActivity">
<Button
android:id="@+id/playBtn"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/play_button_text"
android:background="@drawable/round_button"
/>
</RelativeLayout>
(我将 width/height 设置为 0dp,因为我以编程方式更改了它们。)
问题是在 XML 设计选项卡中,按钮似乎位于屏幕中央(如果我将 width/height 设置为 50dp 进行测试),而我实际上 运行 按钮出现在屏幕左上方的程序。
如何确保按钮实际位于屏幕中央?
这是我设置按钮 width/height 的代码:
int screenWidth = getResources().getDisplayMetrics().widthPixels;
// int screenHeight = getResources().getDisplayMetrics().heightPixels;
Button playBtn = (Button) findViewById(R.id.playBtn);
int playBtnWidth = screenWidth/3;
playBtn.setLayoutParams(new LayoutParams(playBtnWidth, playBtnWidth));
通过以编程方式设置 LayoutParams,您将这些参数中的所有信息重置为默认值(高度和宽度除外,因为您在构造函数中设置了它们)。尝试将 LayoutParams 创建为变量,然后设置布局位置。
LayoutParams params = new LayoutParams(playBtnWidth, playBtnWidth);
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
playBtn.setLayoutParams(params);