Android中怎么自定义控件的declare-styleable属性


要自定义控件的declare-styleable属性,需要在res/values/attrs.xml文件中定义属性,然后在自定义控件的构造方法中获取这些属性。

    在res/values/attrs.xml文件中定义自定义控件的属性,例如:
<resources><declare-styleable name="CustomView"><attr name="customText" format="string" /><attr name="customTextColor" format="color" /><attr name="customTextSize" format="dimension" /></declare-styleable></resources>
    在自定义控件的构造方法中获取这些属性,例如:
public class CustomView extends View {private String customText;private int customTextColor;private float customTextSize;public CustomView(Context context, AttributeSet attrs) {super(context, attrs);TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);customText = a.getString(R.styleable.CustomView_customText);customTextColor = a.getColor(R.styleable.CustomView_customTextColor, Color.BLACK);customTextSize = a.getDimension(R.styleable.CustomView_customTextSize, 12);a.recycle();}// 然后可以在自定义控件中使用这些属性}

这样就可以在布局文件中使用自定义控件并设置这些自定义属性了,例如:

<com.example.CustomViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"app:customText="Hello World"app:customTextColor="@color/colorAccent"app:customTextSize="18sp" />


上一篇:Android ExpandableListView的使用方法是什么

下一篇:Java中的反射机制是什么


android
Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器