android 设置样式,Android:以编程方式设置视图样式

非提供的答案是正确的。

您可以通过编程方式设置样式。

简短的回答是看看[http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/content/Context.java#435]

答案很长。这是我的代码片段,以编程方式为您的视图设置自定义样式:

1)在styles.xml文件中创建样式

#39445B

#8D5AA8

不要忘记在attrs.xml文件中定义自定义属性

我的attrsl.xml文件:

请注意,您可以使用任何名称作为您的样式(我的CustomWidget)

现在让我们以编程方式将样式设置为窗口小部件这是我的简单小部件:

public class StyleableWidget extends LinearLayout {

private final StyleLoader styleLoader = new StyleLoader();

private TextView textView;

private View divider;

public StyleableWidget(Context context) {

super(context);

init();

}

private void init() {

inflate(getContext(), R.layout.widget_styleable, this);

textView = (TextView) findViewById(R.id.text_view);

divider = findViewById(R.id.divider);

setOrientation(VERTICAL);

}

protected void apply(StyleLoader.StyleAttrs styleAttrs) {

textView.setTextColor(styleAttrs.textColor);

divider.setBackgroundColor(styleAttrs.dividerColor);

}

public void setStyle(@StyleRes int style) {

apply(styleLoader.load(getContext(), style));

}

}

布局:

android:id="@+id/text_view"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textSize="22sp"

android:layout_gravity="center"

android:text="@string/styleble_title" />

android:id="@+id/divider"

android:layout_width="match_parent"

android:layout_height="1dp"/>

最后是StyleLoader类的实现

public class StyleLoader {

public StyleLoader() {

}

public static class StyleAttrs {

public int textColor;

public int dividerColor;

}

public StyleAttrs load(Context context, @StyleRes int styleResId) {

final TypedArray styledAttributes = context.obtainStyledAttributes(styleResId, R.styleable.CustomWidget);

return load(styledAttributes);

}

@NonNull

private StyleAttrs load(TypedArray styledAttributes) {

StyleAttrs styleAttrs = new StyleAttrs();

try {

styleAttrs.textColor = styledAttributes.getColor(R.styleable.CustomWidget_customTextColor, 0);

styleAttrs.dividerColor = styledAttributes.getColor(R.styleable.CustomWidget_customDividerColor, 0);

} finally {

styledAttributes.recycle();

}

return styleAttrs;

}

}

您可以在[https://github.com/Defuera/SetStylableProgramatically]找到完整的工作示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值