广告
返回顶部
首页 > 资讯 > 移动开发 >详解Android自定义控件属性
  • 312
分享到

详解Android自定义控件属性

属性Android 2022-06-06 08:06:28 312人浏览 薄情痞子
摘要

在Android开发中,往往要用到自定义的控件来实现我们的需求或效果。在使用自定义 控件时,难免要用到自定义属性,那怎么使用自定义属性呢? 在文件res/values/下新建

Android开发中,往往要用到自定义的控件来实现我们的需求或效果。在使用自定义
控件时,难免要用到自定义属性,那怎么使用自定义属性呢?

在文件res/values/下新建attrs.xml属性文件,中定义我们所需要的属性。


<?xml version="1.0" encoding="utf-8"?>
<resources><!-- resource是跟标签,可以在里面定义若干个declare-styleable -->
  <declare-styleable name="custom_view"><!-- name定义了变量的名称 -->
    <attr name="custom_color" fORMat="color"></attr> <!-- 定义对应的属性,name定义了属性的名称 -->
    <attr name="custom_size" format="dimension"></attr> <!--每一个发生要定义format指定其类型,类型包括 
     reference  表示引用,参考某一资源ID
     string  表示字符串
     color  表示颜色值
     dimension  表示尺寸值
     boolean  表示布尔值
     integer  表示整型值
     float  表示浮点值
     fraction  表示百分数
     enum  表示枚举值
     flag  表示位运算
    -->
 </declare-styleable>

public class CustomTextView extends TextView {
  private int textSize;//自定义文件大小
  private int textColor;//自定义文字颜色
  //自定义属性,会调用带两个对数的构造方法
  public CustomTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.custom_view);//TypedArray属性对象
    textSize = ta.getDimensionPixelSize(R.styleable.custom_view_custom_size, 20);//获取属性对象中对应的属性值 
    textColor = ta.getColor(R.styleable.custom_view_custom_color, 0x0000ff);
    setColorAndSize(textColor, textSize);//设置属性
    ta.recycle();
  }
  public CustomTextView(Context context) {
    super(context);
  }
  private void setColorAndSize(int textColor, int textSize) {
    setTextColor(textColor);
    setTextSize(textSize);
  }
}

<LinearLayout xmlns:android="Http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  xmlns:ldm="http://schemas.android.com/apk/res/com.ldm.learn"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#f6f6f6"
  android:orientation="vertical"
  android:padding="10dp" >
  <com.ldm.learn.CustomTextView
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:text="自定义TextView"
    ldm:custom_color="#333333"
    ldm:custom_size="35sp" />
</LinearLayout>

布局说明:


通过以上几步就可以实现我们想要的自定义属性效果(用自定义属性设置文字大小及颜色)啦!

您可能感兴趣的文章:Android应用开发中自定义ViewGroup视图容器教程Android App中自定义View视图的实例教程android 自定义控件 自定义属性详细介绍android开发教程之自定义属性用法详解Android中自定义控件的declare-styleable属性重用方案Android自定义属性 format的深入解析详解Android自定义控件属性TypedArray以及attrs理解Android中的自定义属性Android UI设计系列之自定义TextView属性实现带下划线的文本框(4)Android如何自定义视图属性


--结束END--

本文标题: 详解Android自定义控件属性

本文链接: https://www.lsjlt.com/news/25645.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作