您的位置:首页 > 移动开发 > Android开发

Android自定义View中代码设置style

2015-06-16 00:53 316 查看
原文地址: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>




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: