android,如何从XML添加ListView项?

我有一个
XML(absolutelayout)模板,我希望我的ListView项看起来如何.

将此项添加到ListView的最佳方法是什么?

另外,还有一件事,如何从java更改ListView的高度?

谢谢! 🙂

最佳答案 像这样制作一个列表视图适配器,(联系人列表的示例)

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;
    }
}

将此适配器设置为列表视图.将xml布局的资源ID传递给此适配器.它会从xml中收缩视图并将其添加到列表视图中.

您还可以在适配器的上述getView()方法中调整listview项的高度.使用LayoutParams ofcourse.

点赞