Reputation: 29
I would like to make a board game like chess (8x8 cell board). As the goal, I hope my application runs on several smartphones like screen dots (= 720px X 1280px, 1024px X 1920px, 1024 X 2340px).
The attached photo is my game board, and make the height equal to its width by input px value. In this result, 1024px X 1920px and 1024 X 2340px are OK.
Of cource, not for 720px X 1280px smartphones.
Could you give me your technics to control TableLayout's height equal to its width ?
<TableLayout
android:id="@+id/TableLayout"
android:layout_width="1080px"
android:layout_height="1080px"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
Upvotes: 0
Views: 126
Reputation: 8867
For fixed number of boxes/grids, I would recommend using GridLayout
or RecyclerView
with GridLayoutManager
. Following is an example of GridLayout
for a 2 X 2 case:
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnCount="2"> //specify number of column each row
<TextView
android:layout_columnWeight="1" //【important!! Not "layout_rowWeight"!!】
android:gravity="center" //center content
android:text="Sam"
android:textColor="@color/black"
android:textSize="30sp" />
<TextView
android:layout_columnWeight="1"
android:gravity="center"
android:text="Sam"
android:textColor="@color/black"
android:textSize="30sp" />
<TextView
android:layout_columnWeight="1"
android:gravity="center"
android:text="Sam"
android:textColor="@color/black"
android:textSize="30sp" />
<TextView
android:layout_columnWeight="1"
android:gravity="center"
android:text="Sam"
android:textColor="@color/black"
android:textSize="30sp" />
</GridLayout>
However, you will notice that its height is not equal to the width, that's because we use match_parent
for the GridLayout
to take the full width of the screen, but we use wrap_content
for its height. So, set match_parent
to the height? No good. Use hard code dp
? No good. Well, turns out that there is an amazing attribute called layout_constraintDimensionRatio
for the ConstraintLayout
:
<androidx.constraintlayout.widget.ConstraintLayout
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">
<GridLayout
android:layout_width="match_parent"
android:layout_height="0dp" //must be 0dp for either width or height
app:layout_constraintDimensionRatio="1:1" //make the ratio 1:1
android:columnCount="2"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
...
</GridLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
There you go.
Upvotes: 2