例子:
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mCustomAdapter = new CustomAdapter(getActivity(), mDataSet);
mRecyclerView.setAdapter(mCustomAdapter);
public class CustomAdapter extends RecyclerView.Adapter {
//This method will inflate the custom_layout and returning the view holder
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_layout, parent, false);
return new ViewHolder(view);
}
//Binding the data into the holder
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textView.setText(mDataSet.get(position));
}
//Getting the count
@Override
public int getItemCount() {
return mDataSet.size();
}
//Creating a view holder class for holding the views
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.text_view);
}
}
}
dependencies {
compile 'com.android.support:recyclerview-v7:26.1.0'
}
此外,还需确认 compileSdkVersion 和 targetSdkVersion 是否已设置为 26+。