首页 > 解决方案 > Kotlin 如何在 TableLayout 中显示图像

问题描述

我正在尝试在 TableLayout 中显示图像。图像已显示,但没有应有的行数和列数(6 行和 4 列 - 见下图!)。

在此处输入图像描述

这是我尝试过的

private fun drawGrid()
    {
        var row: TableRow

        val cellSize: Size = getCellSize();
        val layoutpParams: ViewGroup.LayoutParams = ViewGroup.LayoutParams(cellSize.width, cellSize.height)
        var imageView: ImageView

        _gridElementList = getData()

        var index: Int = 0

        for (i: Int in 0 until settings.row)
        {
            row =  TableRow(this)
            row.layoutParams = layoutpParams

            for (j: Int in 0 until settings.column)
            {
                imageView = ImageView(this);
                imageView.setImageResource(_gridElementList[index].drawableId)

                row.addView(imageView);

                index++
            }

            tableLayout.addView(row);
        }
    }

private fun getCellSize() : Size
{
    windowManager.defaultDisplay.getMetrics(displaymetrics);

    val screenHeight = displaymetrics.heightPixels
    val screenWidth = displaymetrics.widthPixels

    val height: Int = ( screenHeight / settings!!.row).toInt()
    val width: Int = (screenWidth / settings!!.column).toInt()

    return Size(width, height)
}

我需要调整图像大小以始终适合屏幕。矩阵最小为 2x2,最大尺寸为 4 x 8。

活动的xmls:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".GameActivity">

    <TableLayout
        android:id="@+id/tableLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

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

            <TextView
                android:id="@+id/timeLabelTextView"
                android:layout_width="301dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="Eltelt idő"
                android:textAlignment="center"
                android:textSize="24sp" />

            <TextView
                android:id="@+id/timeTextView"
                android:layout_width="168dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="0"
                android:textAlignment="center"
                android:textSize="24sp"
                android:textStyle="bold" />
        </TableRow>
    </TableLayout>
</LinearLayout>

标签: androidkotlinandroid-tablayout

解决方案


推荐阅读