03-17 17:32:58.164 30209-30209/? E/AndroidRuntime: Process: tech.androidstudio.dispatchdemo, PID: 30209
03-17 17:32:58.164 30209-30209/? E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{tech.androidstudio.dispatchdemo/tech.androidstudio.dispatchdemo.MainActivity}: android.view.InflateException: Binary XML file line #3: Error inflating class tech.androidstudio.dispatchdemo.RootLinearLayout
03-17 17:32:58.164 30209-30209/? E/AndroidRuntime: Caused by: android.view.InflateException: Binary XML file line #3: Error inflating class tech.androidstudio.dispatchdemo.RootLinearLayout
03-17 17:32:58.164 30209-30209/? E/AndroidRuntime: at tech.androidstudio.dispatchdemo.MainActivity.onCreate(MainActivity.java:11)
03-17 17:32:58.164 30209-30209/? E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{tech.androidstudio.dispatchdemo/tech.androidstudio.dispatchdemo.MainActivity}: android.view.InflateException: Binary XML file line #3: Error inflating class tech.androidstudio.dispatchdemo.RootLinearLayout
03-17 17:32:58.164 30209-30209/? E/AndroidRuntime: Caused by: android.view.InflateException: Binary XML file line #3: Error inflating class tech.androidstudio.dispatchdemo.RootLinearLayout
03-17 17:32:58.164 30209-30209/? E/AndroidRuntime: at tech.androidstudio.dispatchdemo.MainActivity.onCreate(MainActivity.java:11)
03-17 17:32:58.164 30209-30209/? E/AndroidRuntime: at tech.androidstudio.dispatchdemo.MainActivity.onCreate(MainActivity.java:11)
原因 :缺少构造方法:RootLinearLayout(Context context, AttributeSet attrs)
View(Context ct,AttributeSet set)这个构造在布局xml文件中创建控件的时候自动的调用,如果自定义控件没有这个构造方法,就会抱错。这个含有AttributeSet 的构造方法,应用于布局创建控件,这个AttribteSet attrs 就是XML里面的属性,通过这个属性传给控件.不然控件怎么知道高度时多少,宽度是多少,
解决方法
添加构造方法:RootLinearLayout(Context context, AttributeSet attrs)
package tech.androidstudio.dispatchdemo; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.LinearLayout; /** * Created by Kodulf on 2016/3/17. */ public class RootLinearLayout extends LinearLayout { public RootLinearLayout(Context context) { super(context); } //TODO 一定不能缺少这个构造方法,不然会报错 public RootLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { int action = ev.getAction(); switch (action){ case MotionEvent.ACTION_DOWN: Log.d("Kodulf","RootLinearLayout ACTION_DOWN"); break; } return super.dispatchTouchEvent(ev); } }