2-1 例子
这个例子布局等还和上一篇的例子相似,只是重写了Button和LinearLayout而已,所以效果图不在提供,具体参见上一篇。
首先我们简单的自定义一个Button(View的子类),再自定义一个LinearLayout(ViewGroup的子类),其实没有自定义任何属性,只是重写部分方法(添加了打印,方便查看)而已,如下:
public class TestButton extends Button {
public TestButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.i(null, “TestButton dispatchTouchEvent-- action=” + event.getAction());
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.i(null, “TestButton onTouchEvent-- action=” + event.getAction());
return super.onTouchEvent(event);
}
}
public class TestLinearLayout extends LinearLayout {
public TestLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.i(null, “TestLinearLayout onInterceptTouchEvent-- action=” + ev.getAction());
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
Log.i(null, “TestLinearLayout dispatchTouchEvent-- action=” + event.getAction());
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.i(null, “TestLinearLayout onTouchEvent-- action=” + event.getAction());
return super.onTouchEvent(event);
}
}
如上两个控件很简单吧,不解释,继续看其他代码:
<?xml version="1.0" encoding="utf-8"?><com.zzci.light.TestLinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”
android:orientation=“vertical”
android:gravity=“center”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:id="@+id/mylayout">
<com.zzci.light.TestButton
android:id="@+id/my_btn"
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:text=“click test”/>
</com.zzci.light.TestLinearLayout>
public class ListenerActivity extends Activity implements View.OnTouchListener, View.OnClickListener {
private TestLinearLayout mLayout;
private TestButton mButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLayout = (TestLinearLayout) this.findViewById(R.id.mylayout);
mButton = (TestButton) this.findViewById(R.id.my_btn);
mLayout.setOnTouchListener(this);
mButton.setOnTouchListener(this);
mLayout.setOnClickListener(this);
mButton.setOnClickListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.i(null, “OnTouchListener–onTouch-- action=”+event.getAction()+" --"+v);
return false;
}
@Override
public void onClick(View v) {
Log.i(null, “OnClickListener–onClick–”+v);
}
}
到此基础示例的代码编写完成。没有啥难度,很简单易懂,不多解释了。
2-2 运行现象
当直接点击Button时打印现象如下:
TestLinearLayout dispatchTouchEvent