具有多个项目布局的ListView

And*_*rew 13 layout android listview

我有一个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;
}
Run Code Online (Sandbox Code Playgroud)

R.id.label1并且R.id.label2TextViewsR.layout.layout_A.然而,txtLabel1txtLabel2试图对其进行设置后空.为什么?

我在调试器中逐步完成了这个代码,它膨胀了正确的布局(R.layout.layout_A)并落入下面正确的情况下设置R.id.label1R.id.label2文本.

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

小智 4

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