背景 我正在创建一个自定义组件工具包,用于扩展当前组件的功能,布局和外观。
当前情况:我正在尝试扩展ListView作为概念验证。自定义列表视图与ListView没有什么不同(此时,我只想看到它首先正确加载)。
问题: 当我尝试将布局分配给我的Activity时,应用程序崩溃了。布局引用了我的自定义组件。
错误消息:
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
<?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" />
HelloActivity.java
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));
}
}
HelloListView.java
package org.fs.hello;
import android.content.Context;
import android.widget.ListView;
public class HelloListView extends ListView {
public HelloListView(Context context) {
super(context);
}
}
答案 0 :(得分:24)
它崩溃的原因是android尝试通过调用HelloListView(Context,AttributeSet)来构造HelloListView(使用反射,因为你在xml文件中添加了属性),并且你还没有定义构造函数。
添加:
public HelloListView(Context context,AttributeSet aSet){ super(context,aSet); }
它会更好用!