开发者

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 开发者_如何学JAVAwould 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! :)


<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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜