dbrettschneider dbrettschneider - 1 month ago 18
Android Question

Custom View with XML Layout in Android

I have a ListAdapter with a lot of different layouts for the rows. To have a clean code I want to outsource the layouts for the rows from the getView() of the adapter in View classes. Is it possible to inflate a XML layout into a custom view? I've only found the LayoutInflater but it returns a View and that does not help. I want to have something like the setLayout() of an Activity. Is this possible?

Thanks!

Answer

You can have a custom row view and inflate your xml in its constructor:

public MyRow extends LinearLayout {
    public MyRow(Context context) {
        super(context);
        LayoutInflater.from(context).inflate(R.layout.my_row, this, true);
          ... other initialization ...
    }
}

and then use merge in my_row.xml:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
  ... your row layout ...
</merge>

The merge element causes its children to be added as children of your custom view. Check out Merging Layouts for more info.