ListView有多种布局

时间:2013-08-08 04:17:09

标签: android listview android-arrayadapter

我的情况如下。我有两个布局

首先:

<RelativeLayout ... >
    <TextView id="@+id/textview1" .../>
    <TextView id="@+id/textview2" .../>
    <ImageView .../>
</RelativeLayout>  

第二

<RelativeLayout ... >
    <TextView id="@+id/textview3" .../>
    <TextView id="@+id/textview4" .../>
    <ImageView .../>
</RelativeLayout>

现在我要用这两个布局制作一个列表视图。 ArrayAdapter准备就绪。现在我需要创建一个适配器的新实例,我被困在这里。因为它的构造函数是:

public ArrayAdapter (Context context, 
    int resource, 
    int textViewResourceId, 
    List<T> objects)

context     The current context.
resource    The resource ID for a layout file containing a layout to use when instantiating views.
textViewResourceId  The id of the TextView within the layout resource to be populated
objects     The objects to represent in the ListView.

问题&amp;问题
我不知道如何处理第二和第三个参数。似乎两个参数中的每一个都有多个选择。如何启动适配器?

1 个答案:

答案 0 :(得分:0)

请制作您自己的适配器,可以从BaseAdapter扩展并实现getView()方法,根据您想要的每个项目更改布局。检查这段代码,这可能会有所帮助:

public class MyAdapter extends BaseAdapter{

    private ArrayList<String> data;
    private LayoutInflater inflater;
    public MyAdapter(ArrayList<String> data){
        this.data = data;
        //This is your data from outside

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return data.get(position);
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup arg2) {
        View view = convertView;
        if(view == null){
            if(condition for layout 1){
                // inflate layout 1 to your view here
                            // import data from data.get(position) into you view here
            }else if(condition for layout 2){
                // inflate layout 2 for your view here
                            // import data from data.get(position) into you view here
            }
        }
        return view;
    }

}