我是靠谱客的博主 欣慰雨,这篇文章主要介绍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>
 
 
 

最后

以上就是欣慰雨最近收集整理的关于Android自定义View中代码设置style的全部内容,更多相关Android自定义View中代码设置style内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(36)

评论列表共有 0 条评论

立即
投稿
返回
顶部