I want to resize buttons I added programmatically to my Android app (Java code). They where added to the layout with a default width and height (because of no content). I want them to resize to 1/9 of the screen size to fill the entire screen (9 buttons in a row to fill the screen width). I tried to get the screen width (or the parents container widt, cause it fits to screen width). But got only 0dp.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/tabMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
The buttons where added as children of LinearLaout (width and height match_parent) to tabMain (LinearLayout in ConstraintLayout)
The root ConstraintLayout size is full screen width, but the LinearLayout tabMain is only buttons 9x button width (cause of 9 buttons inserted).
Try using a horizontal linear layout with width match_parent and weightsum 9,
after dynamically adding the buttons inside this layout set their weight to 1 and width to 0dp. This should work.
//I have implemented this for you
Here is the java code :
Button[] buttons=new Button[9];
LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
for (int i=0;i<=8;i++){
buttons[i]=new Button(MainActivity.this);
buttons[i].setText("Button "+(i+1));
buttons[i].setLayoutParams (new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT,1));
ll.addView(buttons[i], new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT,1));
}
Here is the layout :
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:orientation="horizontal"
android:id="@+id/buttonlayout"
android:weightSum="9"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</RelativeLayout>