2015-04-28 24 views
9

Câu hỏi của tôi tương tự như "How to put a CardView attribute in a style", nhưng tôi cần phải đi sâu hơn.Cách thêm thuộc tính CardView vào chủ đề ứng dụng?

Tôi đang sử dụng theme AppCompat, và phong cách của tôi trông giống như

style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> 
    <item name="colorPrimary">@color/toolbar_color</item> 
    <item name="android:listViewStyle">@style/CustomListView</item> 
</style> 

và tôi có thể tạo phong cách riêng cho CardView

<style name="CustomCardView" parent="CardView"> 
    <item name="cardBackgroundColor">@color/card_background</item> 
    <item name="cardCornerRadius">@dimen/card_corner</item> 
</style> 

Tôi có thể gắn nó vào phong cách chính?

+0

Vui lòng kiểm tra [câu trả lời này] (http://stackoverflow.com/a/36005912/2826147). –

Trả lời

5
public View(Context context, AttributeSet attrs, int defStyleAttr) 

@ param defStyleAttr Một thuộc tính trong chủ đề hiện có chứa một tham chiếu tới một tài nguyên phong cách cung cấp các giá trị mặc định cho xem. Có thể là 0 để không tìm kiếm các giá trị mặc định.

Vì vậy, bạn phải làm

attrs.xml

<attr name="myCardViewStyle"/> 

styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> 
    <item name="myCardViewStyle">@style/CustomCardView</item> 
</style> 

<style name="CustomCardView" parent="CardView"> 
    <item name="cardBackgroundColor">@android:color/holo_red_dark</item> 
</style> 

MyCardView.java

public MyCardView(Context context, AttributeSet attrs) { 
    this(context, attrs, R.attr.myCardViewStyle); 
} 

public MyCardView(Context context, AttributeSet attrs, int defStyleAttr) { 
    super(context, attrs, defStyleAttr); 
} 

Vậy đó.

+1

Bạn có thể giải thích vị trí tham chiếu lớp MyCardView trong Mã hoặc Kiểu không? –

+0

@SenthilkumarS Chỉ cần sử dụng nó trong các tệp bố cục của bạn giống như bất kỳ chế độ xem nào khác. ' ...' –

Các vấn đề liên quan