热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

详解Android自定义控件属性

这篇文章主要为大家详细介绍了Android自定义控件属性,需要的朋友可以参考下

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

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

<&#63;xml version="1.0" encoding="utf-8"&#63;>


  
     
     
 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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);
  }
 
}

1
2
3
4
5
<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_="" android:background="#f6f6f6" android:orientation="vertical" android:padding="10dp">
 
  <com.ldm.learn.customtextview android:layout_="" android:text="自定义TextView" ldm:custom_color="#333333" ldm:custom_size="35sp">
 
</com.ldm.learn.customtextview></linearlayout>

布局说明:


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


推荐阅读
author-avatar
田字格
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有