Android自定义View中代码设置style

原文地址:http://www.qylk.blog.163.com/blog/static/1346873562014424101356472/

自定义一个View,可以在该myview.xml中写入该view的style,如:style="@style/mystle",然后使用Inflater.inflate(R.layout.myview,null)获得该view的实例对象。


很多情况下我们可能不想定义一个myview.xml,而是用代码新建一个该对象,因为myview.xml中实在没什么可写的,仅仅是一些style,这时候我们可能想在该view的构造函数中将style添加进去就可以了(实际上可不可行)。例如:
<span style="font-size:24px;">public StyledButton(Context context) {
    super(context, null, <span style="color:#ff0000;">R.style.mystle</span>);
//... whatever
}

public StyledButton(Context context, AttributeSet attrs) {
    super(context, attrs, <span style="color:#ff0000;">R.style.mystle</span>);
//... whatever
}

public StyledButton(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, <span style="color:#ff0000;">R.style.mystle</span>);
//... whatever
}</span>
<span style="font-size:24px;">查看官方文档可知其的确不可以:</span>
<span style="font-size:24px;">The default style to apply to this view. If 0, no style will be applied (beyond what is included in the theme). This may either be an attribute resource, whose value will be retrieved from the current theme, or an explicit style resource.</span>
<span style="font-family:Roboto, sans-serif;font-size:24px;color:#222222;line-height: 19px; white-space: normal; background-color: rgb(249, 249, 249);">
</span>
<span style="font-size:24px;">根据文档,解决的办法是定义一个attr ,并把该attr 放到app的Theme中去,如:</span>
<pre name="code"><span style="font-size:24px;"><resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <item name="@attr/BtnStyle">@style/mystyle</item>
    </style>

    <attr name="BtnStyle" format="reference" />

    <style name="mystyle" parent="@android:style/Widget.Button">
        <item name="android:background">#f00</item>
    </style>

</resources></span>
<span style="font-size:24px;">代码中:</span>
<pre name="code"><span style="font-size:24px;">public class StyledButton extends Button {

 public StyledButton(Context context) {
  super(context, null, R.attr.BtnStyle);
 }

 public StyledButton(Context context, AttributeSet attrs) {
  super(context, attrs, R.attr.BtnStyle);
 }

 public StyledButton(Context context, AttributeSet attrs, int defStyle) {
  super(context, null, R.attr.BtnStyle);
 }
}</span>
<span style="font-size:24px;">最后记得menifest.xml:</span>
<pre name="code" style="color: rgb(34, 34, 34); font-size: 13px; line-height: 18px;"><span style="font-size:24px;"><application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
       <strong> android:theme="@style/AppBaseTheme"</strong> ></span>
 
 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值