java - gridview 列中的自动间距?

标签 java android android-gridview

我有一个简单的 GridView。以下是XML

        <LinearLayout
        android:id="@+id/calendar_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        android:layout_marginRight="@dimen/activity_horizontal_margin"
        android:orientation="vertical" >

       <GridView
            android:id="@+id/grid_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numColumns="7"
            android:verticalSpacing="2dp"
            android:rotationY="180" >
        </GridView>
    </LinearLayout>

我创建一个 TextView 并将其作为 GridView 中的项目插入。基本上,这个想法是创建一个定制的日历。

在我的适配器中

    @Override
public View getView(int position, View convertView, ViewGroup parent) {
    TextView textView = new TextView(mContext);
    textView.setText(days.get(position).toString());
    textView.setRotationY(180);
    textView.setGravity(Gravity.CENTER);

    textView.setBackground(mContext.getResources().getDrawable(R.drawable.grey_box));

    int x = mContext.getResources().getDimensionPixelSize(R.dimen.calendar_slot);
    textView.setLayoutParams(new GridView.LayoutParams(x, x));
    return textView;
}

R.dimen.calendar_slot 等于 30dp。

我不明白的是,鉴于上述原因,为什么我的 gridview 看起来像下面这样? 。我需要将列合并在一起。但他们之间有空间。

有人可以帮忙吗? Screenshot

最佳答案

gridview的列之间有很大空间的原因是你的布局中的textview没有占据grid view提供的完整的列空间

为了避免这个问题,您必须计算设备的屏幕宽度和高度,并将其分别除以列数和行数。这将为您提供单个 TextView 所需的确切宽度和高度。将其设置为 TextView 的尺寸。您的行和列之间将获得相等的间距

代码如下

    DisplayMetrics displayMetrics=getResources().getDisplayMetrics();
    screen_width=displayMetrics.widthPixels;    //width of the device screen
    screen_height=displayMetrics.heightPixels;   //height of device screen

     int view_width=screen_width/columns;   //width for text view
     int view_height=screen_height/rows;   //height for text view

     textview.getgetLayoutParams().width=view_width;
     textview.getgetLayoutParams().height=view_height;

关于java - gridview 列中的自动间距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23152529/

相关文章:

android - 将 Android 搜索栏与拇指对齐

使用套接字上传Java文件,需要上传文件的百分比?

android - 如何在 GridView 布局中将 TextView 添加到 ImageView 中?

安卓 : How to create a customizable time table like structure with scrolling

java - 我在使用 netbeans 时收到此错误 pls 00103

Java 遍历目录中的所有文件和唯一的 RAR 存档

android - 如何通过代码修改marginTop?

android - 如何从 GridView 中获取对象的 itemClick

java - JDBC:调用外部 SQL 脚本,声明 PL/SQL 包

Java InputStream读取问题