-1

i have a listview and I want to use different layout if the ID is different, but I want those data to be on the same listview. example: if id="a", I want to use x1.xml layout else if id="b", I want to use x2.xml layout

this is my code:

    public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    String msg=arrayMsg.get(position);
    ArrayList<String> splitMsg;
    splitMsg=new ArrayList<String>();

    StringTokenizer st=new StringTokenizer(msg,"_");
    for (String token : msg.split("_")) {
        splitMsg.add(token);
    }

    if(convertView==null){
        if(splitMsg.get(0)=="allen")
            convertView=View.inflate(mContext, R.layout.usermsglistview, null);
        else if(splitMsg.get(0)!="allen")
            convertView=View.inflate(mContext, R.layout.friendmsglistview, null);
    }

    if(splitMsg.get(0)=="allen"){
        //do something

    }

    else if(splitMsg.get(0)!="allen"){
        //do something
    }

    return convertView;
}

my problem is it seems like it keeps using the "else if(splitMsg.get(0)!="allen")" condition. So there's only one layout.

4

2 回答 2

4

您不应该strings使用 == 或 != 进行比较。使用equals

if(splitMsg.get(0).equals("allen")){
    //do something

}

else {
    //do something
}
于 2013-07-30T10:49:18.087 回答
0

ListView 拥有多个布局的正确方法是使用 getViewTypeCount() 和 getItemViewType() 方法。

    public static final int TYPE1 = 0;
    public static final int TYPE2 = 1;

    @Override
    public int getViewTypeCount() {
        // Return the count of layouts
        return 2;
    }

    @Override
    public int getItemViewType(int position) {

        String msg=arrayMsg.get(position);

        ArrayList<String> splitMsg;
        splitMsg=new ArrayList<String>();

        for (String token : msg.split("_")) {
            splitMsg.add(token);
        }

        return splitMsg.get(0).equals("allen") ? TYPE1 : TYPE2;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        int layoutType = getItemViewType(position);

        String msg=arrayMsg.get(position);

        if(convertView==null){
            if(layoutType == TYPE1)
                convertView=View.inflate(mContext, R.layout.usermsglistview, null);
            else if(layoutType == TYPE2)
                convertView=View.inflate(mContext, R.layout.friendmsglistview, null);
        }

        if(layoutType == TYPE1) {
            //do something

        }

        else if(layoutType == TYPE2) {
            //do something
        }

        return convertView;
    }
于 2013-07-30T11:04:41.243 回答