根据行创建具有不同类型适配器的视图

时间:2013-12-18 11:23:18

标签: android android-listview android-custom-view

我正在尝试复制此Google即时贴图界面。我并不担心卡的感觉,但我更关心视图是如何构建的。

Google Now Cards

我正在考虑使用一个适配器,它返回与行对应的不同布局。但正如您所看到的,两个视图都包含彼此无关的信息。

是否可以使用具有不同行适配器的ListView?

或者我如何使用自定义视图实现此目的?

2 个答案:

答案 0 :(得分:3)

您需要使用单个适配器执行此操作,并根据列表中的位置对不同的视图进行充气。这个问题的一个很好的答案在这里:

Android ListView with different layouts for each row

答案 1 :(得分:0)

首先,您需要为此创建一个CustomAdapter:

public class CustomAdapter extends BaseAdapter {
    ArrayList<View> views;
    Context context;

    public CustomAdapter(Context context, ArrayList<View> views){
        this.views = views;
        this.context = context;
    }

    @Override
    public int getCount() {
        return views.size();
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View rowView = views.get(i);
        /*set the views of the rowView here but take note use try catch since you can't be sure if the view will be present or not this is the part where I do not advice it to have different custom views per row but it's all yours to do your tricks*/

        return rowView;
    }
}

在这里使用它是我在create:

上的示例方法
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);

        ArrayList<View> views = new ArrayList<View>();

        CustomAdapter adapter = new CustomAdapter(MainActivity.this,views);
        ListView custom_list = (ListView)findViewById(R.id.list_custom);
        custom_list.setAdapter(adapter);

        LayoutInflater inflater = (LayoutInflater)   getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view1 = inflater.inflate(R.layout.view1, null);
        View view2 = inflater.inflate(R.layout.view2, null);

        views.add(view1);
        views.add(view2);
        adapter.notifyDataSetChanged();
}

如果有需要,请解决方法,但基本上就是这样。给视图充气,将它传递给arrayList,然后在listView上设置它。

相关问题