分段ListView

时间:2014-08-27 19:40:46

标签: android listview

我是熟悉Android的iOS开发人员。如何从我的某个iOS应用程序中创建像此表视图一样的分段列表视图? enter image description here

1 个答案:

答案 0 :(得分:0)

我假设您知道如何制作香草列表视图。 (您基本上创建了一个适配器,并通过ListView.setAdapter将此适配器设置为listview)。对于分段列表视图,您需要做一些额外的工作。这里有两种类型的列表项1)应用程序; 2)章节标题。因此,在适配器中,除了getView之外,还需要覆盖getItemViewType和getViewTypeCount。

这是一个代码演示:

public class EnhancedListAdapter extends ArrayAdapter<Item> {

    private static final int TYPE_SECTION = 0;
    private static final int TYPE_APP  = 1;

    // since you only have 2 types
    private static final int TYPE_MAX_COUNT = 2;

    @Override
    public int getItemViewType(int position) {
            // your list object should have a getter to tell what type it is
            switch (getItem(position).getItemType()) {
                case SECTION:
                    return TYPE_TXT_OUT;
                case APP:
                    return TYPE_IMG_OUT;
                default:
                    return -1;
            }

    }

    @Override
    public int getViewTypeCount() {
        return TYPE_MAX_COUNT;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = LayoutInflater.from(context);

        // this is the function you just override
        int type = getItemViewType(position);

        if (convertView == null) {

            switch (type) {
                // I assume you would provide two different row layouts for the Section type and the App type
                case TYPE_SECTION:
                    convertView = inflater.inflate(R.layout.section, null);
                    break;
                case TYPE_APP:
                    convertView = inflater.inflate(R.layout.app, null);
                    break;
            }                
            convertView.setTag(holder);
        } else {
            holder = (MessageItemHolder) convertView.getTag();
        }

        // do your stuffs here

    }

}