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?



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="">
  ... 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.

I alwas use a custom Adapter with a viewholder like:

public class CalendarAdapter extends BaseAdapter {
protected static CalViewHolder holder;
private LayoutInflater mInflater;
public HashMap<Integer,String[]> appointments = new HashMap<Integer,String[]>();

public CalendarAdapter(Context context,HashMap<Integer,String[]> set_appointments) {
    // Cache the LayoutInf
     mInflater = LayoutInflater.from(context);
     appointments = set_appointments;
public int getCount() {
    // TODO Auto-generated method stub
    return appointments == null ? 0:appointments.size();
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return null;
public long getItemId(int arg0) {
    // TODO Auto-generated method stub
    return 0;
public View getView(int position, View convertView, ViewGroup parent) {
     if (convertView == null) {
         convertView = mInflater.inflate(R.xml.appointment, null);
         holder = new CalViewHolder();
         holder.app_lay = (LinearLayout) convertView.findViewById(;
         holder.app_head = (TextView) convertView.findViewById(;
         holder.app_body = (TextView) convertView.findViewById(;
        holder = (CalViewHolder) convertView.getTag();
     return convertView;

static class CalViewHolder {
    LinearLayout app_lay;
    TextView app_head;
    TextView app_body; 


Need Your Help

Global hotkeys in WPF working from every window

c# wpf hotkeys

I have to use hotkeys which will be working from every window and pulpit. In winforms I used:

Within vim's regex engine, why are some metacharacters escaped and some are not?

regex unix vim history vi

Why do you have to escape some metacharacters in their regex engine, but not others? For example: