Android自定义控件及自定义属性

时间:2023-03-09 06:34:59
Android自定义控件及自定义属性

Android自定义控件及自定义属性

自定义控件

创建自定义控件

自定义一个类,继承View

继承View还是哪个类,取决于你要实现一个什么样的控件

如果你要实现的是一个线性布局的组合控件,就可以继承LinearLayout

如果你要实现的是一个布局复杂的组合控件,就可以继承RelativeLayout

具体根据实际情况

这里我要实现一个Android端的显示验证码的控件,我只继承View

package ……;

import ……

/**
* Created by kongqw on 2015/10/23.
*/
public class CheckView extends View {
…… public CheckView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
……
} public void onDraw(Canvas canvas) {
// 画界面
……
} ……
}

类似的,如果你是继承了RelativeLayout,大概可以这样实现

package ……;

import ……

/**
* Created by kongqw on 2015/7/10.
*/
public class KTop extends RelativeLayout { private ……
…… public KTop(Context context) {
super(context);
initView();
} public KTop(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
} public KTop(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
} /**
* 初始化界面
*/
private void initView() {
view = View.inflate(getContext(), R.layout.k_top, this);
// 控件背景
mTitleView = (RelativeLayout) view.findViewById(R.id.title_view);
// 只举一个例子,这里可以获取的布局里的控件
…… } // 做一些其他操作的处理,例如控件的点击事件处理等
…… }

使用自定义控件

在布局文件中的使用

<kong.qingwei.demo.kqwcheckviewdemo.CheckView
android:id="@+id/checkView"
android:layout_width="wrap_content"
android:layout_height="50dp" />

自定义属性

定义自定义属性

在values文件夹下创建attrs.xml文件

name是自定义属性的名称

format是自定义属性的类型,有如下类型,就不一一介绍了

Android自定义控件及自定义属性

代码

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CheckView">
<!-- 随机点数 -->
<attr name="point_num" format="integer" />
<!-- 随机线数 -->
<attr name="point_line" format="integer" />
<!-- 验证码长度 -->
<attr name="text_length" format="integer" />
<!-- 验证码字体大小-->
<attr name="text_size" format="integer" />
<!-- 验证码字体颜色 -->
<attr name="text_color" format="color" />
</declare-styleable>
</resources>

使用自定义属性

在使用自定义控件的xml文件里引入命名空间

xmlns:kongqw="http://schemas.android.com/apk/res-auto"

自定义属性的使用

kongqw:point_num="5"

示例

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:kongqw="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> …… <kong.qingwei.demo.kqwcheckviewdemo.CheckView
android:id="@+id/checkView"
android:layout_width="wrap_content"
android:layout_height="50dp"
kongqw:point_num="5" /> …… </LinearLayout>

效果图

Android自定义控件及自定义属性