Android使用View自定义控件

在实际开发中Android中自带的控件有时无法满足我们的需求,这时就需要我们重写控件来实现我们想要的功能。比如我想使Button有按下和弹起效果还可以写文字,就没有哪个原生的控件能满足我们的需求,在这里我选择重载ImageButton,在ImageButton的基础上添加文字

实现效果

Android使用View自定义控件

重写按钮实现代码

package com.example.buttontest;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageButton;


/**
 * 自定义ImageButton 可以在ImageButton上面设置文字
 */
public class CustomImageButton extends ImageButton {
	private static final String TAG = "CustomImageButton_dzt";
	private String mtext = "a";
	private int mcolor = 0;
	private float mtextsize = 0f;
	private Paint mpatin;

	public CustomImageButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		initAttrs(attrs);
	}

	private void initAttrs(AttributeSet attrs) {
		TypedArray array = getContext().obtainStyledAttributes(attrs,
				R.styleable.CustomButtonAttrs);
		mtext = array.getString(R.styleable.CustomButtonAttrs_textValue);
		mcolor = array.getColor(R.styleable.CustomButtonAttrs_textColor, 230);
		mtextsize = array.getDimension(R.styleable.CustomButtonAttrs_textSize,
				25.0f);
		array.recycle(); // 回收资源
		mpatin = new Paint();
		mpatin.setTextAlign(Align.CENTER);
		Log.d(TAG, "mtextsize = " + mtextsize);
	}

	public void setText(String text) {
		this.mtext = text;
	}

	public void setColor(int color) {
		this.mcolor = color;
	}

	public void setTextSize(float textsize) {
		this.mtextsize = textsize;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		mpatin.setColor(mcolor);
		mpatin.setTextSize(mtextsize);
		canvas.drawText(mtext, canvas.getWidth() / 2,
				(canvas.getHeight() / 2) + 6, mpatin);
	}
}

自定义控件需要注意几点

1.在view类中有三个构造函数

View(Context context)
Simple constructor to use when creating a view from code.
View(Context context, AttributeSet attrs)
Constructor that is called when inflating a view from XML.
View(Context context, AttributeSet attrs, int defStyleAttr)
Perform inflation from XML and apply a class-specific base style.

自定义的控件如果要在xml中定义就要添加带参数的构造函数

public CustomImageButton(Context context, AttributeSet attrs)

并且要调用父类的构造函数

2.如果要在xml中自定义控件的属性

需要解析attrs参数

private void initAttrs(AttributeSet attrs) {
		TypedArray array = getContext().obtainStyledAttributes(attrs,
				R.styleable.CustomButtonAttrs);
		mtext = array.getString(R.styleable.CustomButtonAttrs_textValue);
		mcolor = array.getColor(R.styleable.CustomButtonAttrs_textColor, 230);
		mtextsize = array.getDimension(R.styleable.CustomButtonAttrs_textSize,
				25.0f);
		array.recycle(); // 回收资源
		mpatin = new Paint();
		mpatin.setTextAlign(Align.CENTER);
		Log.d(TAG, "mtextsize = " + mtextsize);
	}
R.styleable.CustomButtonAttrs是自定义的属性

Android使用View自定义控件

attrs.xml定义

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- 自定义按钮控件属性 2014.02.25 -->
    <declare-styleable name="CustomButtonAttrs">
        <attr name="textColor" format="color"></attr>
        <attr name="textSize" format="dimension"></attr>
        <attr name="textValue" format="string"></attr>
    </declare-styleable>

</resources>

自定义控件的使用

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom_btn="http://schemas.android.com/apk/res/com.example.buttontest"
    xmlns:tools="http://schemas.android.com/tools"
    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=".MainActivity" >

    <com.example.buttontest.CustomImageButton
        android:id="@+id/button1"
        style="@style/BtnStyle1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        custom_btn:textValue="@string/rock" />

    <com.example.buttontest.CustomImageButton
        android:id="@+id/button2"
        style="@style/BtnStyle1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/button1"
        custom_btn:textValue="@string/rock" />

    <com.example.buttontest.CustomImageButton
        android:id="@+id/button3"
        style="@style/BtnStyle1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/button2"
        custom_btn:textValue="@string/rock" />

    <com.example.buttontest.CustomImageButton
        android:id="@+id/button4"
        style="@style/BtnStyle1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/button3"
        custom_btn:textValue="@string/rock" />

    <com.example.buttontest.CustomImageButton
        android:id="@+id/button5"
        style="@style/BtnStyle1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/button4"
        custom_btn:textValue="@string/rock" />

    <com.example.buttontest.CustomImageButton
        android:id="@+id/button6"
        style="@style/BtnStyle1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/button5"
        custom_btn:textValue="@string/rock" />

    <com.example.buttontest.CustomImageButton
        android:id="@+id/button7"
        style="@style/BtnStyle2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/button1"
        android:layout_below="@id/button1"
        custom_btn:textValue="@string/rock" />

    <com.example.buttontest.CustomImageButton
        android:id="@+id/button8"
        style="@style/BtnStyle2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/button2"
        android:layout_below="@id/button2"
        custom_btn:textValue="@string/rock" />

    <com.example.buttontest.CustomImageButton
        android:id="@+id/button9"
        style="@style/BtnStyle2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/button3"
        android:layout_below="@id/button3"
        android:layout_marginTop="30dip"
        custom_btn:textValue="@string/rock" />

    <com.example.buttontest.CustomImageButton
        android:id="@+id/button10"
        style="@style/BtnStyle2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/button4"
        android:layout_below="@id/button4"
        custom_btn:textValue="@string/rock" />

    <com.example.buttontest.CustomImageButton
        android:id="@+id/button11"
        style="@style/BtnStyle2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/button5"
        android:layout_below="@id/button5"
        custom_btn:textValue="@string/rock" />

    <com.example.buttontest.CustomImageButton
        android:id="@+id/button12"
        style="@style/BtnStyle2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/button6"
        android:layout_below="@id/button6"
        custom_btn:textValue="@string/rock" />

</RelativeLayout>
解释下面这句话的意思
xmlns:custom_btn="http://schemas.android.com/apk/res/com.example.buttontest"
其中custom_btn是自定义属性的前缀,在后面引用自定义属性时要用到,名字可以随便起

com.example.buttontest为创建程序的包名,不管你自定义的控件放在哪个包下,这里只能用原生的包名

custom_btn:textValue="@string/rock"  这句话就是使用自定义控件的属性

以上xml中用到的样式定义

<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.


    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.


        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

    <!-- 按钮样式 -->
    <style name="BtnStyle1">
        <item name="com.example.buttontest:textColor">#ffff0000</item>
        <item name="com.example.buttontest:textSize">20sp</item>
        <item name="android:layout_marginLeft">10dp</item>
        <item name="android:layout_marginTop">30dp</item>
        <item name="android:background">@drawable/eq_btn_selector</item>
    </style>

    <style name="BtnStyle2">
        <item name="com.example.buttontest:textColor">#ffff0000</item>
        <item name="com.example.buttontest:textSize">20sp</item>
        <item name="android:layout_marginTop">30dp</item>
        <item name="android:src">@drawable/eq_btn_selector</item>
        <item name="android:background">#00000000</item>
    </style>

</resources>

在样式中定义自定义控件的属性时需要添加原生的包名如:com.example.buttontest:textColor

在Activity中使用

package com.example.buttontest;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

	private int moldId = -1;
	CustomImageButton ImageButton1;
	CustomImageButton ImageButton2;
	CustomImageButton ImageButton3;
	CustomImageButton ImageButton4;
	CustomImageButton ImageButton5;
	CustomImageButton ImageButton6;
	CustomImageButton ImageButton7;
	CustomImageButton ImageButton8;
	CustomImageButton ImageButton9;
	CustomImageButton ImageButton10;
	CustomImageButton ImageButton11;
	CustomImageButton ImageButton12;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		ImageButton1 = (CustomImageButton) findViewById(R.id.button1);
		ImageButton2 = (CustomImageButton) findViewById(R.id.button2);
		ImageButton3 = (CustomImageButton) findViewById(R.id.button3);
		ImageButton4 = (CustomImageButton) findViewById(R.id.button4);
		ImageButton5 = (CustomImageButton) findViewById(R.id.button5);
		ImageButton6 = (CustomImageButton) findViewById(R.id.button6);
		ImageButton7 = (CustomImageButton) findViewById(R.id.button7);
		ImageButton8 = (CustomImageButton) findViewById(R.id.button8);
		ImageButton9 = (CustomImageButton) findViewById(R.id.button9);
		ImageButton10 = (CustomImageButton) findViewById(R.id.button10);
		ImageButton11 = (CustomImageButton) findViewById(R.id.button11);
		ImageButton12 = (CustomImageButton) findViewById(R.id.button12);
		ImageButton1.setOnClickListener(new buttonListener());
		ImageButton2.setOnClickListener(new buttonListener());
		ImageButton3.setOnClickListener(new buttonListener());
		ImageButton4.setOnClickListener(new buttonListener());
		ImageButton5.setOnClickListener(new buttonListener());
		ImageButton6.setOnClickListener(new buttonListener());
		ImageButton7.setOnClickListener(new buttonListener());
		ImageButton8.setOnClickListener(new buttonListener());
		ImageButton9.setOnClickListener(new buttonListener());
		ImageButton10.setOnClickListener(new buttonListener());
		ImageButton11.setOnClickListener(new buttonListener());
		ImageButton12.setOnClickListener(new buttonListener());
		moldId = R.id.button3;
		selectBtnState(moldId);
	}

	/**
	 * 选中的按钮状态
	 * 
	 * @param newId
	 */
	private void selectBtnState(int newId) {
		switch (newId) {
		case R.id.button1:
			ImageButton1.setBackgroundResource(R.drawable.eq_btn_sel);
			break;
		case R.id.button2:
			ImageButton2.setBackgroundResource(R.drawable.eq_btn_sel);
			break;
		case R.id.button3:
			ImageButton3.setBackgroundResource(R.drawable.eq_btn_sel);
			break;
		case R.id.button4:
			ImageButton4.setBackgroundResource(R.drawable.eq_btn_sel);
			break;
		case R.id.button5:
			ImageButton5.setBackgroundResource(R.drawable.eq_btn_sel);
			break;
		case R.id.button6:
			ImageButton6.setBackgroundResource(R.drawable.eq_btn_sel);
			break;
		case R.id.button7:
			ImageButton7.setImageResource(R.drawable.eq_btn_sel);
			break;
		case R.id.button8:
			ImageButton8.setImageResource(R.drawable.eq_btn_sel);
			break;
		case R.id.button9:
			ImageButton9.setImageResource(R.drawable.eq_btn_sel);
			break;
		case R.id.button10:
			ImageButton10.setImageResource(R.drawable.eq_btn_sel);
			break;
		case R.id.button11:
			ImageButton11.setImageResource(R.drawable.eq_btn_sel);
			break;
		case R.id.button12:
			ImageButton12.setImageResource(R.drawable.eq_btn_sel);
			break;
		default:
			break;
		}
	}

	/**
	 * 把前一个按钮的状态恢复
	 * 
	 * @param
	 */
	private void regainBtnState(int oldId) {
		switch (oldId) {
		case R.id.button1:
			ImageButton1.setBackgroundResource(R.drawable.eq_btn_selector);
			break;
		case R.id.button2:
			ImageButton2.setBackgroundResource(R.drawable.eq_btn_selector);
			break;
		case R.id.button3:
			ImageButton3.setBackgroundResource(R.drawable.eq_btn_selector);
			break;
		case R.id.button4:
			ImageButton4.setBackgroundResource(R.drawable.eq_btn_selector);
			break;
		case R.id.button5:
			ImageButton5.setBackgroundResource(R.drawable.eq_btn_selector);
			break;
		case R.id.button6:
			ImageButton6.setBackgroundResource(R.drawable.eq_btn_selector);
			break;
		case R.id.button7:
			ImageButton7.setImageResource(R.drawable.eq_btn_selector);
			break;
		case R.id.button8:
			ImageButton8.setImageResource(R.drawable.eq_btn_selector);
			break;
		case R.id.button9:
			ImageButton9.setImageResource(R.drawable.eq_btn_selector);
			break;
		case R.id.button10:
			ImageButton10.setImageResource(R.drawable.eq_btn_selector);
			break;
		case R.id.button11:
			ImageButton11.setImageResource(R.drawable.eq_btn_selector);
			break;
		case R.id.button12:
			ImageButton12.setImageResource(R.drawable.eq_btn_selector);
			break;
		default:
			break;
		}
	}

	class buttonListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (moldId != v.getId()) {
				switch (v.getId()) {
				case R.id.button1:

					break;
				case R.id.button2:

					break;
				case R.id.button3:

					break;
				case R.id.button4:

					break;
				case R.id.button5:

					break;
				case R.id.button6:

					break;
				case R.id.button7:

					break;
				case R.id.button8:

					break;
				case R.id.button9:
					break;
				case R.id.button10:
					break;
				case R.id.button11:
					break;
				}
				regainBtnState(moldId);
				selectBtnState(v.getId());
				moldId = v.getId();
			}
		}
	}
}
在实际使用中遇到一个奇怪的问题在电阻屏上以上代码按钮的点击没有问题,如果在电容屏(支持多点触摸)上,第二行的按钮有可能会出现多个按钮同时选中的状态,这二行按钮不同点在于一个使用setBackgroundResource设置,另一行使用setImageResource在xml中分别对应android:background、android:src一个设置背景图,一个设置前景图,至于为什么使用setImageResource会出现多个被选中,还没有找到根本原因

还有个关于UI体验的问题,就是在onDraw()函数中最好不要去创建对象,否则就提示下面的警告信息:因为onDraw()调用频繁,不断进行创建和垃圾回收会影响UI显示的性能

例如:

protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		Paint mpatin = new Paint();
		mpatin.setTextAlign(Align.CENTER);
		mpatin.setColor(mcolor);
		mpatin.setTextSize(mtextsize);
		canvas.drawText(mtext, canvas.getWidth() / 2,
				(canvas.getHeight() / 2) + 6, mpatin);
	}

Avoid object allocations during draw/layout operations (preallocate and reuse instead) 

示例代码

http://download.csdn.net/detail/deng0zhaotai/7005597

Android使用View自定义控件,布布扣,bubuko.com

Android使用View自定义控件

上一篇:StringBuffer使用append提示String concatenation as argument to 'StringBuffer.append()' call


下一篇:Shell处理用户输入| 学习笔记