最近在学习自定义View,几个简单的自定义View控件的小案例,供大家参考
案例一:主要是熟悉自定义View的步骤
自定义view的步骤:
1.首先创建一个类继承View(或者view的子类TextView什么的都可以,根据实际需求可以自己选择)。
2.实现两个构造方法
3.在 res文件夹下的Value新建文件中新建attrs文件在declare-styleable的标签下重写需要重写的属性
4.在构造方法中重写属性
好了大体的步骤说了,可能还是不直观,下面我就上代码:
1.创建一个类继承View并且实现两个方法,这个案例我们实现一个改变背景的自定义控件的效果
package demo.liuchen.com.android27_customview.SimpleCustom;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import demo.liuchen.com.android27_customview.R;
/**
* Created by ${LC} on 2016/11/22.
* 这是一个最简单的自定义视图只改变View的属性背景颜色
* 步骤:第一步 创建一个类继承View或者View的子类
* 第二步 实现一参数二参数的构造方法(必须实现)
* 第三步 在res文件夹下的value新建文件夹中新建attrs文件夹,重写需要重写的属性
* 第四部 在构造方法中重写属性
*/
public class MyCustomSimpleView extends View{
public MyCustomSimpleView(Context context) {
super(context);
}
/**
*
* @param context 上下文
* @param attrs 希望修改的控件的属性
*/
public MyCustomSimpleView(Context context, AttributeSet attrs) {
super(context, attrs);
/**
* obtainStyledAttributes 获取属性的数组,获取自己定义的属性的数组
* AttributeSet:属性的集合
* StylableRes:资源文件中的Styleable
*
*/
TypedArray typedArray = context.obtainStyledAttributes(
attrs, R.styleable.myCustomSimpleView);
/**
* typedArray.getColor():得到用户的属性值
* int 属性名
* int 默认值
*/
int color = typedArray.getColor(R.styleable.myCustomSimpleView_view_backColor, Color.BLACK);
setBackgroundColor(color);
//回收typeArray
typedArray.recycle();
}
}
2.在res的value文件夹下新建attrs文件然后写入需要自定义的参数
<?xml version="1.0" encoding="utf-8"?> <resources> <!--declare-styleable 头标签用于规定某个控件的属性的集合 name:相当于id 用户在java代码中可通过R.styleable.mycustomSimpleView找到 attr:属性重写 name:再布局文件中重写的属性时用到的属性名 --> <declare-styleable name="myCustomSimpleView"> <attr name="view_backColor" format="color"/> </declare-styleable>
3.自定义控件就定义好了,现在就可以使用了</resources>
我们在Activity的layout文件中直接使用 注意:使用自定义属性的时候必须先声明
xmlns:myapp="http://schemas.android.com/apk/res-auto"
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:myapp="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_custom_simple" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="demo.liuchen.com.android27_customview.SimpleCustom.CustomSimpleActivity"> <!--此处就是自定义View 我们只自定义了背景颜色--> <demo.liuchen.com.android27_customview.SimpleCustom.MyCustomSimpleView android:layout_width="match_parent" android:layout_height="300dp" myapp:view_backColor = "#00f0f0" /> </RelativeLayout>
运行完就是一个背景色为蓝色的背景如图后面还有功能更多的自定义view