I have some XML. In this XML there is a single button inside a relative layout. The relative layout takes up the entire screen. I want the button to have 1/3 of the screen width and height. How could I do this?
Here is the XML:
<?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: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"
android:layout_weight="2">
<Button
android:layout_width="0dp"
android:layout_height="0dp"
android:text="@string/menu_button_text"
android:background="@drawable/round_button"
android:id="@+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
I looked at this question, but even though I assigned a weight to the relative layout itself I could not assign a weight to the button.
you can do this easily in java code.
write this code in oncreate.
Button btn = (Button) findViewById(R.id.button);
int width = getResources().getDisplayMetrics().widthPixels/3;
int height = getResources().getDisplayMetrics().heightPixels/3;
btn.setLayoutParams(new RelativeLayout.LayoutParams(width, heigth));
Percent Support Library is the thing you need.
This library is pretty easy to use since it is just the same RelativeLayout and FrameLayout we are familiar with, just with some additional functionalities.
First of all, since Percent Support Library comes along with Android Support Library 23 so please make sure that you update Android Support Library in SDK Manager to the latest version already. And then add a dependency like below in build.gradle file:
compile 'com.android.support:percent:23.0.0'
Now come back to your Question, you can do something like this for achieving your output. Hope it will help you.
<?xml version="1.0" encoding="utf-8"?>
<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="@drawable/bird"
android:text="Your text"
app:layout_heightPercent="33%"
app:layout_widthPercent="33%" />
</android.support.percent.PercentRelativeLayout>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With