2015-11-05 70 views
0

我想借助theme屬性和一些自定義視圖屬性來設置由其他視圖組成的自定義視圖的主題。 代碼看起來是這樣的:如何在複合自定義視圖上設置主題

IconTextView.java

public class IconTextView extends LinearLayout { 

    public IconTextView(Context context) { 
     super(context); 
     init(context, 0); 
    } 

    public IconTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(context, 0); 
    } 

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

    private void init(Context context, int defStyleAttr) { 
     LayoutInflater inflater = LayoutInflater.from(context); 
     inflater.inflate(R.layout.view_icon_text, this, true); 
    } 
} 

attrs_icon_text_view.xml

<declare-styleable name="IconTextViewTheme"> 
    <attr name="textViewStyle" format="reference" /> 
    <attr name="iconStyle" format="reference" /> 
</declare-styleable> 

view_icon_text.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:orientation="horizontal" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 

    <ImageView 
     style="?iconStyle" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center" 
     android:src="@android:drawable/ic_menu_share" 
     android:contentDescription="@null" /> 

    <TextView 
     style="?textViewStyle" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center" 
     tools:text="Hello"/> 
</LinearLayout> 

styles.xml

<resources> 
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">  
    </style> 

    <style name="Custom.IconTextView" parent="AppTheme"> 
     <item name="android:textColor">@color/colorPrimary</item> 
     <item name="android:textSize">30sp</item> 
     <item name="android:padding">8dp</item> 
    </style> 

    <style name="Custom.Test" parent="AppTheme"> 
     <item name="textViewStyle">@style/Special.IconTextView</item> 
    </style> 
</resources> 

layout_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:orientation="horizontal" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 

    <IconTextView 
     app:theme="@style/Custom.Test" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 
</LinearLayout> 

不幸的是,在Android Studio預覽這隻能如果主題是通過預覽的主題選擇器選擇。它不適用於theme屬性。

不應該theme屬性應用主題中包含的樣式到視圖及其子級? 這是甚至可能的,還是應該將主題應用於整個活動?

回答

相關問題