I’m trying to extend a LinearLayout to use as a composite component. I have followed this tutorial:
link
Which seems fairly straight forward. However when I try to inflate my component it fails all the time. The error I get from logCat is that my class can’t be found. It seems strange to me that as far as I can see android searches for my component among it’s own components (I’m unsure about the correct wording here, please se below).
The code I have written is as follows:
main (the current activity):
//just the ordinary autogenerated eclipse code...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
My extended linear layout:
public class DialPadView extends LinearLayout {
public DialPadView(Context ctx, AttributeSet attr) {
super(ctx, attr);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
((Activity)getContext()).getLayoutInflater().inflate(R.layout.dialpadview, this);
}
}
My main.xml layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<whalenut.testinflate.DialPadView
android:id="@+id/mydialpad"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/></LinearLayout>
and finally my dialpadview.xml file to use with my composite component:
<?xml version="1.0" encoding="utf-8"?>
<DialPadView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="test"/>
</DialPadView>
ofcourse all my class files resides in the package whalenut.testinflate
logCat says this:
java.lang.RuntimeException: Unable to start activity ComponentInfo{whalenut.testinflate/whalenut.testinflate.TestInflateActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class DialPadView
…
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class DialPadView
…
Caused by: java.lang.ClassNotFoundException: android.view.DialPadView in loader dalvik.system.PathClassLoader[/data/app/whalenut.testinflate-2.apk]
Why is Dalvik(?) searching for my class in the package android.view instead of whalenut.testinflate when I have given the fully qualified classname in the xml-file, is it because it doesn’t find it there to begin with?
In short why can’t I, or rather how do I inflate a extended Layout in android?
You need to change your DialPadView as follows:
Then call this in your constructor:
You can then use the following in your main activity:
I hope this helps!