添加RecyclerView
Android Material风格的应用(一)--AppBar TabLayout
Android Material风格的应用(二)--RecyclerView
Android Material风格的应用(三)--DrawerLayout
Android Material风格的应用(四)--FloatActionButton
Android Material风格的应用(五)--CollapsingToolbar
工程源码 添加对应的支持库
compile 'com.android.support:recyclerview-v7:24.2.1'
compile 'com.android.support:cardview-v7:24.2.1'
添加 res/layout/recycler_view.xml
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recycler_view"
android:clipToPadding="false"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:scrollbars="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
</android.support.v7.widget.RecyclerView>
在ListContentFragment.java
TileContentFragment.java
和 CardContentFragment.java
中
分别创建各自的ContentAdapter,在onCreateView方法中初始化RecyclerView相关的内容
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
RecyclerView recyclerView = (RecyclerView)inflater.inflate(R.layout.recycler_view,container,false);
ContentAdapter adapter = new ContentAdapter(recyclerView.getContext());
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),2));
return recyclerView;
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public ImageView imageView;
public TextView textView;
public ViewHolder(LayoutInflater inflater,ViewGroup parent) {
super(inflater.inflate(R.layout.item_tile,parent,false));
imageView = (ImageView)itemView.findViewById(R.id.title_picture);
textView = (TextView)itemView.findViewById(R.id.title_title);
}
}
public static class ContentAdapter extends RecyclerView.Adapter<ViewHolder>{
private static final int LENGTH = 18;
private String[] names;
private Drawable[] avatars;
public ContentAdapter(Context context) {
Resources resources = context.getResources();
names = resources.getStringArray(R.array.places);
TypedArray a = resources.obtainTypedArray(R.array.places_picture);
avatars = new Drawable[a.length()];
for(int i = 0;i<a.length();i++){
avatars[i] = a.getDrawable(i);
}
a.recycle();
}
@Override
public int getItemCount() {
return LENGTH;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.imageView.setImageDrawable(avatars[position % avatars.length]);
holder.textView.setText(names[position % names.length]);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()),parent);
}
}
来源:oschina
链接:https://my.oschina.net/u/2997378/blog/787632