Android應用開發:CardView的使用及兼容

引言


在Google I/O 2014上,Google公佈了Android L Preview版本,此版本的UI有了非常大的改變,很炫很給力!同時,Google也給出了兩個可以向下兼容的控件放到了V7包中,分別是RecyclerView和CardView,這篇博文就說一下怎麼使用CardView。


CardView的包在哪?


雖然說CardView整合到了V7中,但是在support-v7中並不能發現,通過查看sdk extra路徑下的文件可以發現,其名字叫cardview-v7。


這個路徑下就有cardview相關的東西了,包括已經打包好的aar包。


依賴


如果應用是以Gradle構建的,引用CardView就很簡單了:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:cardview-v7:21.0.0-rc1'
}

如果Gradle提示找不到,就證明你的SDK需要更新了,把Google support包更新到最新吧。


如果沒有用Gradle構建,就需要找到jar包引用進來,而jar包隱藏在CardView的aar文件中:


以壓縮包方式打開aar,提取出其中的class.jar,這個jar文件就可以當作庫文件進行依賴了。


依賴添加完成後,進行編譯會發現出現minSdk錯誤,cardview-v7的minsdk爲“L",其實CardView能夠向下兼容到2.0。

在Android gradle tools 0.11版本後,可以通過xml中的tools配置進行節點替換,而AndrodiStudio對gradle tools的支持更好一些,其ParentIDE Intellij都不行,所以目前我能找到的正常使用CardView的IDE及配置辦法只有在AndroidStudio中,不過這也是趨勢,早用早好的事情。


解決辦法:

在使用CardView的工程的AndroidManifest.xml中:

<uses-sdk
        xmlns:tools="http://schemas.android.com/tools"
        tools:node="replace" />
意思就是在做AndroidoManifest.xml編譯時,採用替換的策略,即全部使用build.gradle中定義的屬性作爲最終屬性。添加完成後,再次編譯,問題解決。


使用


在使用CardVIew之前,要明白CardView是個什麼東西。CardView如Linearlayout、Framelayout一樣都是ViewGroup,即其他控件的容器。CardView繼承於Framelayout,所以Framelayout的屬性他都有,同時CardView還有幾個特殊的屬性:


在API21(Android L)等級以上擁有屬性elevation,意爲CardView的Z軸陰影,只有L平臺有效。只能通過xml中的elevation屬性指定;

其餘(2.0以上)有屬性cardBackgroundColor,意爲CardView的卡片顏色,只能通過xml的cardBackgroundColor進行指定;

其餘(2.0以上)有屬性cardConerRadius,意爲CardView卡片的四角圓角矩形程度,單位dimen(dp px sp),可以通過xml指定,也可以通過代碼中的setRadius指定。


示例:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardview"
    app:cardCornerRadius="8dp"
    app:cardBackgroundColor="@color/black"
    android:layout_margin="8dp"
    android:layout_height="80dp"
    android:layout_width="match_parent">

    <TextView
        android:text="TextView in CardView"
        android:layout_gravity="center"
        android:textSize="26sp"
        android:textColor="@color/l_white"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</android.support.v7.widget.CardView>

效果圖:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章