Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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://scheR_778_11845@as.android.com/apk/res/android"
  //自定义@L_666_5@myView的命名空间
  xmlns:gu="http://scheR_778_11845@as.android.com/apk/res/com.gu.myrect"
  xmlns:tools="http://scheR_778_11845@as.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如何自定义视图属性所遇到的程序开发问题。

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。