Как равномерно разделить таблицы в сетке? - PullRequest
0 голосов
/ 10 апреля 2019

Я пытаюсь воссоздать следующий макет в Android:

result

Сетка не должна динамически расти, она всегда будет 5 столбцами и 2 строками.Ориентация привязана к ландшафту.Каждая ячейка имеет одинаковую компоновку, только данные в TextViews могут изменяться.

Мой текущий подход - заполнить GridLayout с помощью TableLayouts и установить соответствующие layout_row & layout_column для каждого TableLayout.Вот так:

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:rowCount="2" 
    android:columnCount="4" 
    android:orientation="vertical">

<TableLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_row="0"
    android:layout_column="0"
    android:background="@color/colorAccent">

Что приводит к этому:

bad Код с картинки выше: https://pastebin.com/khr9aGWf

Я бегув несколько проблем.

  • Я не могу заставить ячейки автоматически масштабироваться, чтобы соответствовать экрану.
  • Размер этого файла макета начинает становиться очень большим и трудным для управления

Возможно, мой подход совершенно неправильный, и мне нужно пойти к чему-то, где я определю разметку ячейки и динамически заполню ею сетку?

Любая помощь будет принята с благодарностью.

1 Ответ

2 голосов
/ 11 апреля 2019

Вы можете создать этот вид макета, используя GridView

<GridView
android:id="@+id/list"
android:numColumns="5"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"/>

макет вашего элемента gridview

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_row="1"
    android:layout_column="0"
    android:background="@color/colorPrimary">

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

        <TextView
            android:id="@+id/textView9"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />
    </TableRow>
</TableLayout>

GridviewAdapter.java

    public class GridviewAdapter extends BaseAdapter {

    Activity context;
    private LayoutInflater mInflater;
    TableLayout.LayoutParams params;

    public GridviewAdapter(Activity context)
    {
        this.context=context;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        params=new TableLayout.LayoutParams(new TableLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                (int) ((getDeviceHeight(context)-getStatusBarHeight()) / 2)));

    }

    @NonNull
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        final ViewHolder holder;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item, null);

            holder = new ViewHolder();

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if(position%2==0)
        {
            convertView.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));
        }else{
            convertView.setBackgroundColor(context.getResources().getColor(R.color.colorPrimary));
        }

        convertView.setLayoutParams(params);


        return convertView;
    }
    @Override
    public int getCount() {
        return 10;
    }

    @Override
    public String getItem(int position) {
        return "";
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private class ViewHolder {

    }

    public static int getDeviceHeight(Context context) {

        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            Point point = new Point();
            wm.getDefaultDisplay().getSize(point);
            return point.y;
        } else {
            return wm.getDefaultDisplay().getHeight();
        }
    }

    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

}

и в вашей деятельностикласс добавить код, подобный этому

GridviewAdapter itemsAdapter = new GridviewAdapter(this);
 GridView listView = (GridView) findViewById(R.id.list);
 listView.setAdapter(itemsAdapter);

ваш вывод выглядит как this

...