Amod Gokhale
Amod Gokhale

Reputation: 2438

Android TableLayout - add buttons dynamically at center of screen

Please see below screenshot for different results on tablet and on phones.

activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/frameLayout1"
android:weightSum="4"
android:padding="0dp"
android:orientation="vertical">

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="centerCrop"
    android:src="@drawable/crossword_background"/>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="0dp"
    android:orientation="vertical"
    android:id="@+id/frameLayout"
    android:weightSum="4"
    >
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/transparent" >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/tvTitle"
                style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
                android:layout_width="100dp"
                android:layout_height="24dp"
                android:layout_marginStart="4dp"
                android:layout_marginTop="4dp"
                android:layout_marginEnd="4dp"
                android:layout_marginBottom="4dp"
                android:background="@drawable/count_frame"
                android:fontFamily="@font/roboto"
                android:gravity="center"
                android:textColor="#5A0FC8"
                android:textSize="13sp"
                android:textStyle="bold"
                tools:text="4" />

        <TextView
            android:id="@+id/menu_item_score"
            style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
            android:layout_width="100dp"
            android:layout_height="24dp"
            android:layout_margin="4dp"
            android:background="@drawable/count_frame"
            android:gravity="right"
            android:layout_alignParentRight="true"
            android:textColor="#5A0FC8"
            android:textSize="13sp"
            android:textStyle="bold"
            android:textAlignment="center"
            tools:text="4" />
        </RelativeLayout>
    </androidx.appcompat.widget.Toolbar>

    <LinearLayout
        android:id="@+id/rightLayout"
        android:layout_width="40dp"
        android:layout_height="fill_parent"
        android:layout_alignParentEnd="true"
        android:layout_below="@id/horizontal_divider"
        android:orientation="vertical" >
        <LinearLayout
            android:layout_weight="1"
            android:layout_height="fill_parent"
            android:layout_width="match_parent"
            android:weightSum="4"
            android:orientation="vertical" >


            <ImageButton
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:src="@drawable/ic_action_360"
                android:background="@null"/>
            <ImageButton
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:src="@drawable/ic_action_360"
                android:background="@null"/>
            <ImageButton
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:src="@drawable/ic_action_360"
                android:background="@null"/>
            <ImageButton
                android:id="@+id/ShowHint"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:src="@drawable/ic_action_360"
                android:background="@null"/>

        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/leftLayout"
        android:layout_width="40dp"
        android:layout_height="fill_parent"
        android:layout_alignParentStart="true"
        android:layout_below="@id/horizontal_divider"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_weight="1"
            android:layout_height="fill_parent"
            android:layout_width="match_parent"
            android:weightSum="4"
            android:orientation="vertical" >


            <ImageButton
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:src="@drawable/ic_action_360"
                android:background="@null"/>
            <ImageButton
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:src="@drawable/ic_action_360"
                android:background="@null"/>
            <ImageButton
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:src="@drawable/ic_action_360"
                android:background="@null"/>
            <ImageButton
                android:id="@+id/ShuffleButtons"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:src="@drawable/ic_action_360"
                android:background="@null"/>

        </LinearLayout>

    </LinearLayout>

    <View
        android:id="@+id/horizontal_divider"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_centerVertical="true" />


    <RelativeLayout
        android:id="@+id/firstLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="0dp"
        android:layout_centerInParent="true"
        android:layout_margin="0dp"
        android:layout_above="@+id/horizontal_divider"
        android:layout_below="@id/toolbar"
        android:gravity="center">

        <TableLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tblLayout"
            android:gravity="center"
            android:padding="0dip"
            android:shrinkColumns="*"
            android:layout_margin="0dip"
            android:layout_centerInParent="true"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true">
        </TableLayout>


    </RelativeLayout >


    <LinearLayout
        android:id="@+id/secondLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/horizontal_divider"
        android:layout_toStartOf="@id/rightLayout"
        android:layout_toEndOf="@id/leftLayout"
        android:orientation="vertical" >
        <FrameLayout
            android:id="@+id/frame_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="5dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginBottom="5dp"
            >

        </FrameLayout>

    </LinearLayout>
</RelativeLayout>

background_ic_btn_bonus.xml

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_btn_bonus"
    android:tileMode="disabled" android:gravity="center" >
</bitmap>

background_ic_btn_default.xml

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_btn_default"
    android:tileMode="disabled" android:gravity="center" >
</bitmap>

Corresponding Java Code

    String[] iLayoutMap = getTableLayout();
    /*
    iLayoutMap contains split rows removing 2 
    2,0,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,1,1,1,0,2,0,0,0,1,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0*/
    TableLayout tableLayout  = (TableLayout) findViewById(R.id.tblLayout);

    for(int i=1;i<iLayoutMap.length;i++){
        TableRow NewRow1 =new TableRow(this);
        NewRow1.setPadding(0, 0, 0, 0);
        NewRow1.setGravity(Gravity.CENTER);
        NewRow1.setHorizontalGravity(Gravity.CENTER);
        NewRow1.setVerticalGravity(Gravity.CENTER);

        String [] items = iLayoutMap[i].split("\\s*,\\s*");
        NewRow1.setWeightSum(items.length-1);
        for(int j = 0; j < items.length;j++) {
            if(items[j].equalsIgnoreCase("0")){


                Button btnAdd = new Button(context);
                btnAdd.setGravity(Gravity.CENTER);
                btnAdd.setTextSize(25);
                btnAdd.setTextColor(Color.WHITE);

                //btnAdd.setPadding(10   ,10,10,10);
                //btnAdd.setBackgroundResource(R.drawable.ic_btn_default);
                btnAdd.setBackgroundResource(R.drawable.background_ic_btn_default);
                btnAdd.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,TableRow.LayoutParams.WRAP_CONTENT ,1));
                NewRow1.addView(btnAdd);
            }else if(items[j].equalsIgnoreCase("1")){

                //https://stackoverflow.com/questions/3404582/adding-text-to-imageview-in-android



                Button btnAdd = new Button(context);
                String strId = Integer.toString(i) + Integer.toString(j-1);
                //btnAdd.setWidth(iObjectWidth);
                //btnAdd.setHeight(iObjectHeight);
                btnAdd.setId(Integer.valueOf(strId));
                btnAdd.setGravity(Gravity.CENTER);
                btnAdd.setTextSize(25);
                btnAdd.setTextColor(Color.WHITE);

                //btnAdd.setPadding(10   ,10,10,10);
                //btnAdd.setBackgroundResource(R.drawable.ic_btn_default);
                btnAdd.setBackgroundResource(R.drawable.background_ic_btn_bonus);
                btnAdd.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,TableRow.LayoutParams.WRAP_CONTENT,1 ));
                NewRow1.addView(btnAdd);
            }
        }
        NewRow1.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,TableLayout.LayoutParams.WRAP_CONTENT,items.length-1));
        tableLayout.addView(NewRow1);
    }

Function

public String[] getTableLayout() {

    if (lvlinfo != null) {
        return lvlinfo.getLayout().split("2");
    }

    //Return this as default in case of failure
    String arr = "2,0,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,1,1,1,0,2,0,0,0,1,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0";
    //String arr = "2,0,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,1,1,1,0,2,0,0,0,1,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0";
    return arr.split("2");

}

Expected Result ( Working correctly on Tablet with Android 4.4.2 with below code)

enter image description here

Actual Results ( Tested on multiple phones with OS >= 8.1.0) enter image description here

Expected Result ( Working correctly on Tablet with Android 4.4.2 with below code with layout bounds)

Actual Results ( Tested on multiple phones with OS >= 8.1.0 without layout bounds)

Upvotes: 1

Views: 336

Answers (2)

AskNilesh
AskNilesh

Reputation: 69681

I Have tried your code but unable to reproduce this output

For me your code is working fine check the output

as per my opinion you should use

You should use RecyclerView with GridLayoutManager

Follow this sample code

Add one recyclerview in your activity layout xml file

<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/firstLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="0dp"
        android:gravity="center">

    <androidx.recyclerview.widget.RecyclerView
            android:layout_width="wrap_content"
            android:id="@+id/gridRecyclerView"
            android:layout_centerInParent="true"
            android:layout_height="wrap_content"/>

</RelativeLayout>

Now inside your activity set GridLayoutManager to your RecyclerView

GridLayoutManager (Context context, 
                int spanCount)

Creates a vertical GridLayoutManager

Parameters

context Context: Current context, will be used to access resources.

spanCount int: The number of columns in the grid

    import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class JavaActivity extends AppCompatActivity {

    RecyclerView myRecyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_java);
        myRecyclerView = findViewById(R.id.gridRecyclerView);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(JavaActivity.this, 6);
        myRecyclerView.setLayoutManager(gridLayoutManager);
        myRecyclerView.setAdapter(new MyAdapter(this));

    }
}

Create one adapter class RecyclerView like this

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private Context context;

    public MyAdapter(Context context) {
        this.context = context;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.row_list_item, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        if (position%2==0){
            holder.imgBanner.setBackgroundColor(Color.BLUE);

        }else {
            holder.imgBanner.setBackgroundColor(Color.GREEN);
            holder.imgBanner.setImageResource(R.drawable.red_heart);
        }
    }

    @Override
    public int getItemCount() {
        return 36;
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView imgBanner;


        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            imgBanner = itemView.findViewById(R.id.imgBanner);

        }
    }
}

Create one layout file for RecyclerView item

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_margin="2dp"
                android:orientation="vertical">

    <ImageView
            android:id="@+id/imgBanner"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:contentDescription="@string/app_name"
    />

</RelativeLayout>

Upvotes: 1

Yavor Mitev
Yavor Mitev

Reputation: 1508

Try with a padding like this:

<RelativeLayout
            android:id="@+id/firstLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="someDp"   ->>>> Padding
            android:paddingRight="someDp" ->>>> Padding
            android:layout_above="@+id/horizontal_divider"
            android:layout_below="@id/toolbar"
            android:gravity="center">
    <TableLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/tblLayout"
                android:gravity="center"
                android:shrinkColumns="*"
                android:padding="0dip"
                android:layout_margin="0dip"
                android:layout_centerInParent="true"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"></TableLayout>
</RelativeLayout >

Upvotes: 0

Related Questions