dbrettschneider dbrettschneider - 1 year ago 175
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?


Answer Source

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

public MyRow extends LinearLayout {
    public MyRow(Context 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 ...

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download