首页 > 代码库 > Android RecyclerView And CardView
Android RecyclerView And CardView
Google I/O 2014大会公布Android L系统,还有Material Design全新的设计风格.而Material Design卡片式的设计.Google Play应用商店和G+ APP已经变成这样的卡片式的风格.为了配合Material Design, Google特意在SDK中加入了RecyclerView 和 CardView,只是它加入在Support-V7库中,可能是为了兼容旧版本号吧.Google官方已经说明确怎么用了,这里: https://developer.android.com/preview/material/get-started.html, 只是还不够完整.
以下就看看怎么使用RecyclerView 及 CardView展示卡片式的ListView.思路和ListView一模一样. 我使用的是Android Studio,用Eclipse的朋友...赶紧转到Android Studio来吧.
1, SDK更新到最新.API 20 及Build Tool 20.0.0
2,新建一个普通的project,API Level>=15.
3,build.gradle中引入Support-V7.
dependencies { compile 'com.android.support:recyclerview-v7:+' compile 'com.android.support:cardview-v7:+' }
假设仅仅这样写会出现下面的错误:
Error:Execution failed for task ‘:app:processDebugManifest‘.
> Manifest merger failed : uses-sdk:minSdkVersion 15 cannot be smaller than version L declared in library com.android.support:recyclerview-v7:21.0.0-rc1
这是由于导入了v7的21.0.0rc1,可是这个不支持API 15.有一个Hack的解决的方法:在AndroidManifest.xml文件里写入:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="robam.org.ltest"> <uses-sdk tools:node="replace" /> </manifest>
点击同步button,这时候就把V7的recyclerview和cardview导入了project.
4, 接下来,Activity的布局文件,相当于ListView :
<android.support.v7.widget.RecyclerView android:id="@+id/my_recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="vertical" />5,在接下来,写Item的布局文件, Item布局根节点是CardView,这样就会有卡片式的阴影效果.
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:layout_marginTop="4dp" android:layout_marginBottom="4dp" app:cardCornerRadius="3dp"> <TextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingLeft="?6, 到写Activity的时候了.例如以下:android:listPreferredItemPaddingLeft" android:paddingRight="?android:listPreferredItemPaddingRight" android:paddingTop="16dp" android:paddingBottom="16dp" android:textColor="@android:color/holo_blue_light" tools:text="Item" /> </android.support.v7.widget.CardView>
public class MainActivity extends Activity { public static final List<String> data; static { data = http://www.mamicode.com/new ArrayList();> 完毕之后的效果就和ListView一模一样了.
上面的源码戳这里:http://pan.baidu.com/s/1mgoN8uc
这个样例參考自: https://github.com/evant/recyclerview-sample/tree/master
另附上一篇英文教程: http://antonioleiva.com/recyclerview/
事实上早有国外的大牛写了一个开源库已经实现了这样的效果,并且还有非常多Card的效果.慢慢探索吧.
https://github.com/gabrielemariotti/cardslib
Android RecyclerView And CardView