Roger
Roger

Reputation: 6527

android, how to add ListView items from XML?

I have an XML ( absolutelayout ) template, of how I want my ListView items to look like.

What would be the best way to add this items to my ListView?

On, and one more thing, how do I change ListView's height from java?

Thanks! :)

Upvotes: 4

Views: 21334

Answers (2)

Nikola Despotoski
Nikola Despotoski

Reputation: 50578

<ListView android:id="@+id/list" android:layout_width="fill_parent"
    android:layout_height="0dip" android:focusable="false" android:layout_weight="1" />

    <TextView android:id="@+id/empty" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:gravity="center"
        android:text="Loading" android:visibility="invisible" />

</LinearLayout>

This is how I mean to add your item VIEWS. Then fill your items with data.

Changing listview height or any other descriptives can be achieved with modifying Layout.Params

Upvotes: 2

Sharique Abdullah
Sharique Abdullah

Reputation: 655

Make an list view adapter like this, (Sample for a contact list)

public class ContactListAdapter extends ArrayAdapter<Contact>
{

    private int resource;

    public ContactListAdapter(Context context, int resource, List<Contact> items)
    {
        super(context, resource, items);

        this.resource = resource;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ViewHolder holder = null;
        LinearLayout contactListView;

        if (convertView == null)
        {
            contactListView = new LinearLayout(getContext());
            String inflater = Context.LAYOUT_INFLATER_SERVICE;
            LayoutInflater layoutInflater;
            layoutInflater = (LayoutInflater) getContext().getSystemService(inflater);
            layoutInflater.inflate(resource, contactListView, true);

            holder = new ViewHolder();

            holder.textViewName = (TextView) contactListView.findViewById(R.id.name);
            holder.textViewAddress = (TextView) contactListView.findViewById(R.id.address);

            contactListView.setTag(holder);
        }
        else
        {
            contactListView= (LinearLayout) convertView;

            holder = (ViewHolder) contactListView.getTag();
        }

        Contact item = getItem(position);

        holder.textViewName.setText(item.getName());
        holder.textViewAddress.setText(item.getAddress());

        return contactListView;
    }

    protected static class ViewHolder
    {
        TextView textViewName;
        TextView textViewAddress;
    }
}

Set this adapter to your listview. Pass in the resource id of your xml layout to this adapter. It would deflate the view from the xml and add it to the listview.

You can also adjust the heights of the listview items in the above getView() method of the adapter. Using LayoutParams ofcourse.

Upvotes: 0

Related Questions