开发者

ListViews with multiple item layouts

开发者 https://www.devze.com 2023-01-10 04:16 出处:网络
I have a ListView on my ListActivity and I\'d like the rows of the ListView to be 1 of 3 different layouts.The first item in my list is always going to use layout A, the second item in my list is alwa

I have a ListView on my ListActivity and I'd like the rows of the ListView to be 1 of 3 different layouts. The first item in my list is always going to use layout A, the second item in my list is always going to use layout B, and all subsequent items are going to use layout C.

Here is my getView function:

@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.l开发者_高级运维ayout_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 and R.id.label2 are TextViews on R.layout.layout_A. However, txtLabel1 and txtLabel2 are null after trying to set them. Why?

I stepped through this code in the debugger and it inflated the correct layout (R.layout.layout_A) and fell into the correct case below to set the R.id.label1 and R.id.label2 text.

Also, if there is a better way to do this, please let me know.


Looks like "View v = convertView; if (v == null) {..." is a problem. You should re-create view every time because you don't know the type of given view. Also, you can use viewholder approach for more efficient implementation. You can find some ideas in this blog: http://codinglines.frankiv.me/post/18486197303/android-multiple-layouts-in-dynamically-loading

0

精彩评论

暂无评论...
验证码 换一张
取 消