在Android Training中,看到CardView使用自定义属性时有点特别,如下:
<style name="Widget.SampleDashboard.Card" parent="Widget">
<item name="android:gravity">center</item>
<item name="android:layout_margin">@dimen/card_margin</item>
<item name="cardCornerRadius">4dp</item>
<item name="cardElevation">5dp</item>
<item name="contentPadding">@dimen/card_padding</item>
</style>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- The CardView needs to be wrapped to ensure spacing is applied correctly. -->
<android.support.v7.widget.CardView
style="@style/Widget.SampleDashboard.Card"
android:layout_width="match_parent"
android:layout_height="wrap_content">
自定义的属性值是通过style导入的,并没有直接在layout文件中设置; 而且layout文件中也不需要加入xmlns:cardview="http://schemas.android.com/apk/res/com.example.android.navigationdrawer"这类申明(蓝色字体部分是工程包名),简化了使用流程。
而之前我常采用的方式:在layout中申明xmlns:cardview="http://schemas.android.com/apk/res/com.example.android.navigationdrawer", 然后在layout文件中直接设置自定义属性值,如:cardview:cardCornerRadius = "4dp"。感觉更麻烦些。