Android 主題樣式中的自訂屬性值的擷取方式

來源:互聯網
上載者:User

標籤:

擷取自訂屬性通常是在自訂View內部擷取,但在某種方式下,無論自訂View的屬性還是主題中樣式的屬性,均可在外部style中擷取。


由於非自訂View的外部擷取方式比較複雜,這裡暫時略過,後續補充。

自訂attr

<?xml version="1.0" encoding="utf-8"?><resources xmlns:android="http://schemas.android.com/apk/res/android">    <attr name="theme_name" format="string|reference"/></resources>

設定attr

<resources>    <!-- Activity themes -->    <style name="Theme.Base" parent="android:Theme.Holo.Light" >    <item name="theme_name" >@string/theme_name_1</item>        </style></resources>

擷取

TypedValue outValue = new TypedValue();getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,outValue, true);textView.setBackgroundResource(outValue.resourceId);

注意,如果我直接設定資料,則resourceId為0

<resources>    <!-- Activity themes -->    <style name="Theme.Base" parent="android:Theme.Holo.Light" >    <item name="theme_name" >我的主題</item>        </style></resources>

這時候我們的資料可以使用TypeValue.string讀取

TypedValue outValue = new TypedValue();getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,outValue, true);if(outValue.data==TypeValue.TYPE_STRING){textView.setBackgroundResource(outValue.string);}

當然,有時候我們的屬性可能是個集合,這時候不能用TypedValue擷取,TypeValued只能判斷類型,因此我們選擇如下方式

public int getTabContainerHeight()    {        TypedArray a = mContext.obtainStyledAttributes(null, android.support.v7.appcompat.R.styleable.ActionBar, android.support.v7.appcompat.R.attr.actionBarStyle, 0);        int height = a.getLayoutDimension(android.support.v7.appcompat.R.styleable.ActionBar_height, 0);        Resources r = mContext.getResources();        if(!hasEmbeddedTabs())            height = Math.min(height, r.getDimensionPixelSize(android.support.v7.appcompat.R.dimen.abc_action_bar_stacked_max_height));        a.recycle();        return height;    }


對於View內部擷取方式如下

  private static Context themifyContext(Context context, AttributeSet attrs, int defStyleAttr)    {        TypedArray a = context.obtainStyledAttributes(attrs, android.support.v7.appcompat.R.styleable.Toolbar, android.support.v7.appcompat.R.attr.ActionBarStyle, 0);        int themeId = a.getResourceId(android.support.v7.appcompat.R.styleable.Toolbar_theme, 0);        if(themeId != 0)            context = new ContextThemeWrapper(context, themeId);        a.recycle();        return context;    }


Android 主題樣式中的自訂屬性值的擷取方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.