Moresby
Moresby

Reputation: 79

Android Custom Component doesn't show anything after inflate

Trying to create a custom component that gets it's layout from an XML file (box.xml). I have gone through a couple of tutorials but just can't seem to get anything to display. Below is the constructors for my custom component and the code does get executed without errors.

public class MyView extends LinearLayout {
    //Constructor required for inflation from resource file
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);        
        LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view=layoutInflater.inflate (R.layout.box, this);                        
        Log.d("CONSTRUCTOR 2", "TESTER");        
    }
}

I add the component to a layout with this:

<com.mysample.MyView android:layout_width="50dp" android:layout_height="38dp" android:background="#FF000000" />

The black block does appear on the screen but not with the layout of the xml file I inflate it with.

Upvotes: 0

Views: 1852

Answers (1)

Kumar Bibek
Kumar Bibek

Reputation: 9117

You will need to add the created view to the linear layout.

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        View view = inflate(context, R.layout.box, null);
        addView(view);
    }

This should work. Do you see the Log in your Logcat by the way?

Here is the box.xml (Sample one). You need to use the fully qualified class name of the MyView wherever you want to use it.

<?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">
<com.beanie.samples.drawing.MyView
android:id="@+id/whiteboardView1" android:layout_width="fill_parent"
android:layout_height="fill_parent"></com.beanie.samples.drawing.MyView>
</LinearLayout>

Check this sample project here.

Upvotes: 2

Related Questions