回收站中的间距查看项目

时间:2018-11-04 23:22:32

标签: android android-recyclerview

我遇到无法解决的问题。我用谷歌搜索,但无法得到即时解决方案。我有一个回收视图,如下所示:

<android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:paddingBottom="70dp"
        android:layout_marginTop="@dimen/activity_vertical_margin"

此回收视图在屏幕上显示如下 enter image description here

如果您注意到,每个项目的文本上方和文本底部都没有空格。最有可能是由于wrap_content。我想在顶部和底部的项目单元格内添加空间。像这张图片 enter image description here

如果您注意到了,我会画红色箭头指示每个项目列表中心的多余空间和文本。如何在单元格内添加空间(文本顶部的空间和文本底部的空间?左右空间也会很酷。

当我用谷歌搜索时,我只找到在项目之间添加空格的代码。但是我正在寻找的是像第二张图片一样在单元格项本身中增加间距。我将感谢您的帮助。预先感谢

2 个答案:

答案 0 :(得分:1)

您必须在回收项目中添加填充。如果您使用的是Android的默认项目布局,建议您创建自己的布局。

答案 1 :(得分:1)

您的回收站视图肯定使用了适配器,而该适配器负责创建子代。正如@cocored所说,您必须创建自己的布局。您必须在适配器中执行此操作(通常在onCreateViewHolder中)。 您可以使用充气器服务为每个孩子充气xml布局。

recyclerview_child.xml

<?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="horizontal"
    android:padding="10dp">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>

    ...

</LinearLayout>

然后在您的适配器中执行类似的操作

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private List<Whatever> mData;
    private LayoutInflater mInflater;

    MyRecyclerViewAdapter(Context context, List<Whatever> data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // inflates the child layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_child, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each child
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Whatever obj = mData.get(position);
        holder.myTextView.setText(obj.getName());
        ...
    }

    // total number of children
    @Override
    public int getItemCount() {
        return mData.size();
    }

    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder{
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.tv);
        }
    }
}

希望有帮助

相关问题