在RecyclerView适配器中使用自定义视图?

use*_*732 14 android android-adapter android-view android-recyclerview

我有一个基本的自定义视图,如下所示:

public class CustomView extends RelativeLayout {

    private User user;

    private ImageView profilePicture;

    public CustomView(Context context) {
        super(context);
        init();
    }

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        inflate(getContext(), R.layout.custom_layout, this);

        profilePicture = (ImageView) findViewById(R.id.profilePicture);

        // ACCESS USER MODEL HERE
        // e.g. user.getUsername()
    }

}
Run Code Online (Sandbox Code Playgroud)

如您所见,我想在View中访问用户数据(即:)user.getUsername().

我还需要能够在RecyclerView适配器中使用自定义视图.

这是我的适配器目前的​​样子:

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

    private Context context;

    private List<User> userData;

    public MyAdapter(Context context, List<User> userData) {
        this.context = context;
        this.userData = userData;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(View v) {
            super(v);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);

        // HOW TO INFLATE THE CUSTOM VIEW?

        // ViewHolder viewHolder = new ViewHolder(customView);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        // ANYTHING HERE?
    }

    @Override
    public int getItemCount() {
        return userData.size();
    }

}
Run Code Online (Sandbox Code Playgroud)

如何在适配器中充气自定义视图?
另外,我应该放什么onBindViewHolder()

注意:我必须使用自定义视图,因为我在不同的适配器下使用此视图(即:不仅仅是此RecyclerView适配器).

Ale*_*ers 23

假设一个CustomView类看起来像这样:

public class CustomView extends RelativeLayout {
    private User user;
    private ImageView profilePicture;

    // override all constructors to ensure custom logic runs in all cases
    public CustomView(Context context) {
        this(context, null);
    }
    public CustomView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }
    public CustomView(
            Context context,
            AttributeSet attrs,
            int defStyleAttr,
            int defStyleRes
    ) {
        super(context, attrs, defStyleAttr, defStyleRes);

        // put all custom logic in this constructor, which always runs
        inflate(getContext(), R.layout.custom_layout, this);
        profilePicture = (ImageView) findViewById(R.id.profilePicture);
    }

    public void setUser(User newUser) {
        user = newUser;
        // ACCESS USER MODEL HERE
        // e.g. user.getUsername()
    }
}
Run Code Online (Sandbox Code Playgroud)

RecyclerView.AdapterRecyclerView.ViewHolder可能是这个样子:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    // no Context reference needed—can get it from a ViewGroup parameter
    private List<User> userData;

    public MyAdapter(List<User> userData) {
        // make own copy of the list so it can't be edited externally
        this.userData = new ArrayList<User>(userData);
    }

    @Override
    public int getItemCount() {
        return userData.size();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // no need for a LayoutInflater instance—
        // the custom view inflates itself
        CustomView itemView = new CustomView(parent.getContext());
        // manually set the CustomView's size
        itemView.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        ));
        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.getCustomView().setUser(userData.get(position));
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private CustomView customView;

        public ViewHolder(View v) {
            super(v);
            customView = (CustomView) v;
        }

        public CustomView getCustomView() {
            return customView;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
  • CustomView管理自己的设置,发生在自己的构造,在这种情况下,使用XML文件的通货膨胀.(或者,它可以以编程方式设置其子视图.)
  • 因此,RecyclerView.Adapter不需要执行任何通货膨胀 - 它只是创建一个新CustomView实例,并让人CustomView担心自己的设置.
  • 在调用其方法之前CustomView无法获取User实例setUser,因此在构造函数中不能进行用户访问.在任何情况下,在CustomView一生中,a RecyclerView可以要求它在不同时间显示许多不同用户的信息.将CustomView需要能够做到这一点.因此,setUser介绍了一种方法.
  • 因为它CustomView是由代码而不是XML实例化的,所以不能在XML中定义大小的属性.因此,在定时之后以编程方式完成大小调整.
  • onBindViewHolder简单地调用setUserCustomView链接中CustomView使用正确的User实例.
  • ViewHolder类现在只需之间的链接RecyclerView项目和CustomView.

似乎从未讨论过使用RecyclerViews中其他类的预构建自定义视图(即不在其中RecyclerView.Adapter扩展XML ).我认为即使自定义视图专门用于a中RecyclerView,这也是一个很好的主意,因为它促进了关注点的分离对单一责任原则的遵守.

  • 这是一个很好的答案-在最后一段中,它变成了一个很棒的答案。我已经开始在所有RecyclerView适配器中使用自定义视图,结果是如此干净 (3认同)
  • 谢谢,卢克-感谢您的赞赏。我仍然感到惊讶的是,这种方法在我看到的项目中没有被更频繁地采用。 (2认同)

Jin*_*ose -2

列表内容.xml

<?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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">

    <TextView
        android:text="TextView"
        android:layout_width="@dimen/_160sdp"
        android:textSize="@dimen/_14sdp"
        android:layout_gravity="center|bottom"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:paddingTop="@dimen/_10sdp"
        android:id="@+id/name"
         />

    <ImageView
        android:layout_width="@dimen/_20sdp"
        android:layout_gravity="center|right"
        android:layout_height="@dimen/_20sdp"
        app:srcCompat="@drawable/close"
        android:id="@+id/close"
        android:layout_weight="1" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

适配器.java

public class yourAdapter extends RecyclerView.Adapter<yourAdapter .SimpleViewHolder> {


private Context mContext;
ArrayList<String> mylist;

public yourAdapter (Context context, ArrayList<String> checklist) {
    mContext = context;
    mylist = checklist;
}

@Override
public yourAdapter .SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_content, parent, false);
    return new yourAdapter .SimpleViewHolder(view);
}
@Override
public void onBindViewHolder(final yourAdapter .SimpleViewHolder holder, final int position) {
    holder.name.setText(adap.getName());


}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public int getItemCount() {
    return mylist.size();
}

@Override
public int getItemViewType(int i) {
    return 0;
}

public static class SimpleViewHolder extends RecyclerView.ViewHolder {
    TextView name;
    Imageview content;


    public SimpleViewHolder(View itemView) {
        super(itemView);
        name= (TextView) itemView.findViewById(R.id.name);
        close= (Imageview) itemView.findViewById(R.id.close);

    }
}
Run Code Online (Sandbox Code Playgroud)

}

然后在activity中你想要的地方调用适配器类

https://developer.sonymobile.com/2010/05/20/android-tutorial-making-your-own-3d-list-part-1/


归档时间:

查看次数:

12080 次

最近记录:

7 年,10 月 前