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>