具有多个项目布局的ListView

时间:2010-08-05 15:35:34

标签: android listview layout

我的ListView上有一个ListActivity,我希望ListView的行是3种不同布局中的一种。我列表中的第一项始终使用布局A,列表中的第二项始终使用布局B,所有后续项目将使用布局C.

这是我的getView函数:

@Override
public View getView(int position, View convertView, ViewGroup parent) { 
    // get the View for this list item
    View v = convertView;
    if (v == null) {
        LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        switch (position) {
            case 0:
                v = vi.inflate(R.layout.layout_A, parent, false);
                break;
            case 1:
                v = vi.inflate(R.layout.layout_B, parent, false);
                break;
            default:
                v = vi.inflate(R.layout.layout_C, parent, false);
                break;
        }
    }   
    switch (position) {
        case 0:
            TextView txtLabel1 = (TextView)findViewById(R.id.label1);
            TextView txtLabel2 = (TextView)findViewById(R.id.label2);
            if (txtLabel1 != null) {
                txtLabel1.setText("sdfasd");
            }
            if (txtLabel2 != null) {
                txtLabel2.setText("dasgfadsasd");
            }
            break;
        default:
            break;
    }
    // return the created view
    return v;
}
R.id.label1上{p} R.id.label2TextViewsR.layout.layout_A。但是,txtLabel1txtLabel2在尝试设置后为空。为什么?

我在调试器中逐步执行了此代码,并且它使正确的布局(R.layout.layout_A)膨胀,并在下面的正确情况下设置R.id.label1R.id.label2文本。

此外,如果有更好的方法,请告诉我。

1 个答案:

答案 0 :(得分:4)

看起来像“View v = convertView; if(v == null){...”是个问题。您应该每次都重新创建视图,因为您不知道给定视图的类型。此外,您可以使用查看器方法来实现更高效的实施。您可以在此博客中找到一些想法:http://codinglines.frankiv.me/post/18486197303/android-multiple-layouts-in-dynamically-loading

相关问题