目錄
2. 在attr.xml中,爲自定義 style 賦值,編寫自己需要的 style 風格
一、概述
前情提要:
其實在Android控件是不支持通過java代碼動態設置Style的,雖然系統沒有暴露設置style的接口,但是我們可以另闢蹊徑
思路:
1.通過declare-styleable自定義style,定義自己需要的屬性
2.然後通過style設置默認值
3.java 動態中動態解析
通過java代碼動態設置控件 style效果圖:
二、代碼示例
在project 的 values 目錄下,創建一個 attr.xml
1.在attr.xml中聲明自定義 style 屬性
分別是左右 padding 和 背景
<!--自定義 Style 屬性-->
<declare-styleable name="LImageStyle">
<attr name="lleftPadding" format="dimension" />
<attr name="lrightPadding" format="dimension" />
<attr name="lbackgroud" format="reference" />
</declare-styleable>
2. 在attr.xml中,爲自定義 style 賦值,編寫自己需要的 style 風格
<!--描述自定義 style-->
<style name="LImageStyle_A">
<item name="lleftPadding">@dimen/dp10</item>
<item name="lrightPadding">@dimen/dp10</item>
<item name="lbackgroud">@android:color/holo_red_light</item>
</style>
<!--描述自定義 style-->
<style name="LImageStyle_B">
<item name="lleftPadding">@dimen/dp20</item>
<item name="lrightPadding">@dimen/dp20</item>
<item name="lbackgroud">@android:color/holo_blue_bright</item>
</style>
<!--系統原生 style
在 xml 中直接複製即可,
此處效果和 styleA 一樣-->
<style name="LImageStyle_Default">
<item name="android:paddingLeft">@dimen/dp10</item>
<item name="android:paddingRight">@dimen/dp10</item>
<item name="android:background">@android:color/holo_red_light</item>
</style>
注意:
自定義style 屬性,如 lbackgroud,在 佈局文件中通過 style:屬性指定是不生效的,
因爲控件的style屬性只會解析系統原生的。
此處通過 style 屬性指定默認 style
默認 style 中的屬性都是系統原生的,所以生效
<ImageView
android:id="@+id/demo_style_iv"
android:layout_width="@dimen/dp100"
android:layout_height="@dimen/dp100"
android:layout_gravity="center_horizontal"
style="@style/LImageStyle_Default"
android:src="@drawable/test2_bg"/>
3. 在java 代碼中動態解析
/**
* 描述:動態解析 style
*/
private void parseStyle(@StyleRes int styleId) {
TypedArray array = obtainStyledAttributes(styleId, R.styleable.LImageStyle);
int leftPaddiong = (int) array.getDimension(R.styleable.LImageStyle_lleftPadding, 0);
int rightPadding = (int) array.getDimension(R.styleable.LImageStyle_lrightPadding, 0);
Drawable drawable = array.getDrawable(R.styleable.LImageStyle_lbackgroud);
mImageView.setPadding(leftPaddiong,mImageView.getPaddingTop(),rightPadding,mImageView.getPaddingBottom());
if(drawable != null){
mImageView.setBackgroundDrawable(drawable);
}
array.recycle();
}
4. 調用動態解析
mButton.setOnClickListener(v -> {
if(isStyleA){
parseStyle(R.style.LImageStyle_B);
isStyleA = false;
mTextView.setText("當前 style:B");
mButton.setText("切換爲:StyleA");
}else {
parseStyle(R.style.LImageStyle_A);
isStyleA = true;
mTextView.setText("當前 style:A");
mButton.setText("切換爲:StyleB");
}
});