Textview 在 GridView 中被裁剪

Textview getting clipped in GridView

我正在学习如何使用 gridview 并开始开发示例应用程序来构建基本计算器。

我的想法是使用 gridview 来保存单元格。 gridview 使用一个 TextAdapter(扩展 BaseAdapter),其中 returns 一个与传递的位置相对应的 TextView。

我现在可以设置所有内容以显示 0-9 的数字,但文本视图似乎在右侧被剪裁了。这是我面临的问题

这是我的 XML

MainActivity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:textAlignment="center">

    <TextView android:text="@string/hello_world" android:layout_width="fill_parent"
        android:layout_height="48dp"
        android:textIsSelectable="true"
        android:id="@+id/textView" />

    <GridView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/calculatorCellsView"

        android:layout_marginTop="100dp"

        android:numColumns="5"
        android:columnWidth="20dp"
        android:clickable="true"
        android:choiceMode="singleChoice"
        android:visibility="visible"
        android:verticalSpacing="2dp"
        android:horizontalSpacing="2dp"
        android:gravity="center"
        />


</RelativeLayout>

cellLayoutOfGridView xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/id_gridCell"
        android:background="@drawable/view_background"
        android:gravity="center"
        />

</LinearLayout>

绘制边框的可绘制背景

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <stroke android:color="#000000" android:width="4dp"/>
    <solid android:color="@color/background_material_light"/>
    <padding android:bottom="4dp" android:left="4dp" android:right="4dp" android:top="4dp"/>
</shape>

我发现问题出在 Adapter 的 getView() 函数定义覆盖了布局参数。从 java 文件中删除它修复了它!

如果不使用 LinearLayout,请尝试删除它。
cellLayoutOfGridView.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/id_gridCell"
    android:background="@drawable/view_background"
    android:gravity="center"
    android:layout_gravity="center" />

您可以看到是什么导致网格单元格内的视图被推到右侧。
对于 KitKat:转到 设置 > 开发者选项 > 显示布局边界
对于 Lollipop:转到 设置 > 开发者选项 > 显示布局边界
重新打开您的应用程序。现在您可以看到视图边距和填充。
如果您没有发现问题,也可以在此处 post 截图。