自定义控件

本文介绍如何在Android中自定义Button控件,包括实现点击改变颜色的功能,并通过KevinButton类演示了自定义事件处理过程。此外,还展示了如何将自定义控件集成到布局文件中。

1. 自定义控件分两类, 继承View做功能扩展, 继承ViewGroup做复合控件




自定义一个button为例, 如何自定义事件

KevinButton.java  控件

package com.example.uitest;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.widget.Button;

public class KevinButton extends Button {

	private KevinClickListener kevinClickListener;
	
	public KevinButton(Context context) {
		super(context);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		Paint paint = new Paint();
		paint.setColor(Color.RED);
		canvas.drawRect(5, 5, 30, 30, paint);
	}
	
	public interface KevinClickListener{
		public void clickChangeColor();
	}
	
	public void setKevinClickListener(KevinClickListener kevinClickListener){
		this.kevinClickListener = kevinClickListener;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_UP:
			long time = event.getEventTime()-event.getDownTime();
			if(time >= 2000 ){
				kevinClickListener.clickChangeColor();
				System.out.println("Time():"+time );
			}
			break;

		default:
			break;
		}
		
		return super.onTouchEvent(event);
	}
	
}
SelfButtonActivity.java ;  activity

public class SelfButtonActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		final KevinButton bt = new KevinButton(this);
		bt.setKevinClickListener(new KevinClickListener() {
			@Override
			public void clickChangeColor() {
				Toast.makeText(SelfButtonActivity.this, "clickChangeColor", Toast.LENGTH_LONG).show();
				bt.setBackgroundColor(Color.GREEN);
			}
		});
		
		setContentView(bt);
	}
	
}
如果将自定义控件放入到xml layout中的两种方法

如果控件是内部类,则用第2中view, 引用内部类的时候用$

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <com.example.uitest.KevinButton />
    <view class="com.example.uitest.KevinButton"/>

</LinearLayout>


 











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值