I have a button that I am trying to make in the center of the 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>
(I set the width/height to 0dp because I programmatically change them.)
The problem is while while in the XML design tab the button appears to be in the center of the screen (if I set the width/height to 50dp for testing) when I actually run the program the button appears in the top left of the screen.
How do I make sure the button is actually in the center of the screen?
Here is the code where I set the width/height of the button:
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));