自定义Android组件正在使充气机上的应用程序崩溃

自定义Android组件正在使充气机上的应用程序崩溃,android,Android,背景: 我正在创建一个自定义组件工具包,扩展当前组件的功能、布局和外观 当前情况:我正在尝试扩展ListView作为概念证明。自定义列表视图与ListView没有什么不同(在这一点上,我只想先看到它被正确加载) 问题: 当我尝试为活动分配布局时,应用程序正在崩溃。布局引用了我的自定义组件 错误消息: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{org.fs.hel

背景: 我正在创建一个自定义组件工具包,扩展当前组件的功能、布局和外观

当前情况:我正在尝试扩展ListView作为概念证明。自定义列表视图与ListView没有什么不同(在这一点上,我只想先看到它被正确加载)

问题: 当我尝试为活动分配布局时,应用程序正在崩溃。布局引用了我的自定义组件

错误消息:

FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{org.fs.hello/org.fs.hello.HelloActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class org.fs.hello.HelloListView
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class org.fs.hello.HelloListView
Caused by: java.lang.NoSuchMethodException: HelloListView(Context,AttributeSet)

代码 hello.xml


它崩溃的原因是android试图通过调用HelloListView(Context,AttributeSet)来构造HelloListView(使用反射,因为您在xml文件中添加了属性),而您尚未定义该构造函数

加:

公共HelloListView(上下文,属性集aSet){ 超级(上下文,aSet); }


而且它会工作得更好

Oops定义了除Android在膨胀时试图使用的构造函数之外的所有构造函数。
<?xml version="1.0" encoding="utf-8"?>
<org.fs.hello.HelloListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/hello_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
package org.fs.hello;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class HelloActivity extends Activity {
    private HelloMsg[] messages = new HelloMsg[] {
            new HelloMsg("Hey there!", "Nick"),
            new HelloMsg("Hey. How are you?", "Corrine"),
            new HelloMsg("I'm doing good. How about you?", "Nick"),
            new HelloMsg("Not to shabby.", "Corrine"),
            new HelloMsg("Hey guys!", "Tyler"),
            new HelloMsg("Hey Tyler", "Nick"),
            new HelloMsg("Hey Tyler", "Corrine"),
            new HelloMsg("Well I've got to go.", "Corrine"),
            new HelloMsg("See you later", "Nick"),
            new HelloMsg("Bye", "Tyler"),
            new HelloMsg("Bye", "Corrine")
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hello); //Error is thrown here

        HelloListView hListView = (HelloListView)findViewById(R.id.hello_view);
        hListView.setAdapter(new ArrayAdapter<HelloMsg>(this, R.layout.list_item, messages));
    }
}
package org.fs.hello;

import android.content.Context;
import android.widget.ListView;

public class HelloListView extends ListView {
    public HelloListView(Context context) {
        super(context);
    }
}