自定义的LinearLayout 使用报错 android.view.InflateException: Binary XML file line #3: Error inflating class

在创建自定义的LinearLayout时遇到Android的InflateException,原因是缺少`RootLinearLayout(Context context, AttributeSet attrs)`构造方法。这个构造方法用于布局XML文件中创建控件时调用,传入的AttributeSet用于获取XML属性,如宽度、高度等设置。" 96427183,4896335,应用程序隐私政策详解,"['隐私保护', '数据安全', '用户信息', '法律合规', '网络服务']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:     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);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值