如何在RecyclerView中正确显示网格?

时间:2017-07-10 13:38:12

标签: android android-layout android-recyclerview

我正在开发一款现在展示热门电影的应用。它使用TMDB API来获取此数据。我使用RecyclerView在包含2列的网格中显示可点击的ImageView。 这是我想要实现的结果: an edge to edge grid of all movies我只能通过硬编码值来实现:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">`

    <ImageView
        android:layout_width="185dp" <!--HARDCODED VALUES-->
        android:layout_height="278dp"<!--HARDCODED VALUES-->
        android:contentDescription="@string/movie"
        android:id="@+id/rv_image_view" />

</LinearLayout>  

如果我使用layout_width="match_parent"layout_height="wrap_content",我会得到非常奇怪和偏斜的结果。 Like this one.我该如何解决这个问题? 请不要将此标记为重复。我为此搜索得很远,但绝对没有想到。

2 个答案:

答案 0 :(得分:1)

尝试这样创建一个像这样的布局文件

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

    <ImageView
    android:id="@+id/movies_item"
    android:layout_width="185dp" 
    android:layout_height="278dp"
    android:scaleType="fitXY"/>

</LinearLayout>

活动:

 RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 2);
    recyclerView.setLayoutManager(layoutManager);

答案 1 :(得分:1)

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

    <ImageView
        android:scaleType="fitXY"
        android:id="@+id/movies_item"
        android:layout_width="match_parent"
        android:layout_height="180dp"/>

</LinearLayout>