Android Material風格的應用(一)--AppBar TabLayout
Android Material風格的應用(二)--RecyclerView
Android Material風格的應用(三)--DrawerLayout
Android Material風格的應用(四)--FloatActionButton
Android Material風格的應用(五)--CollapsingToolbarjava
工程源碼 添加對應的支持庫android
compile 'com.android.support:recyclerview-v7:24.2.1' compile 'com.android.support:cardview-v7:24.2.1'
添加 res/layout/recycler_view.xml
git
<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相關的內容github
@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); } }