Android如何自定义视图属性

Android如何自定义视图属性,第1张

概述本文实例为大家介绍了Android自定义视图属性的方法,供大家参考,具体内容如下

本文实例为大家介绍了AndroID自定义视图属性的方法,供大家参考,具体内容如下

1. 自定义一个自己的视图类继承自VIEw

public class MyVIEw extends VIEw{  public MyVIEw(Context context,AttributeSet attrs)  {    super(context,attrs);    //获取到自定义的属性    TypedArray ta=context.obtainStyledAttributes(attrs,R.styleable.MyVIEw);    int color=ta.getcolor(R.styleable.MyVIEw_rect_color,0xffff0000);    setBackgroundcolor(color);    //必须手动回收ta    ta.recycle();  }  public MyVIEw(Context context)  {    super(context);  }}

2. 在res/values目录中新建一个attrs.xml文件

<?xml version="1.0" enCoding="utf-8"?><resources>  //定义一个declare-styleable标签,在里面设置attr属性  <declare-styleable name="MyVIEw">    <attr name="rect_color" format="color"/>  </declare-styleable></resources>

一个attr属性,对应了一个视图属性

3.最后看布局文件中如何利用我们创建的自定义视图并设置其属性

<linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"  //自定义一个MyVIEw的命名空间  xmlns:gu="http://schemas.androID.com/apk/res/com.gu.myrect"  xmlns:tools="http://schemas.androID.com/tools"  androID:layout_wIDth="match_parent"  androID:layout_height="match_parent"  androID:orIEntation="vertical" >  <com.gu.myrect.MyVIEw    androID:layout_wIDth="100dp"    androID:layout_height="100dp"    //根据自定义的命名空间和我们在attrs中设置的属性,自定义属性值    gu:rect_color="#cc99cc" /></linearLayout>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android如何自定义视图属性全部内容,希望文章能够帮你解决Android如何自定义视图属性所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1148740.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存