当前位置: 移动技术网 > IT编程>移动开发>Android > Android如何自定义视图属性

Android如何自定义视图属性

2019年07月24日  | 移动技术网IT编程  | 我要评论

占蕈釜钰,越南女兵档案,男子率众捉奸暴打男小三

本文实例为大家介绍了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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网