使用getItemViewType() - 我如何知道哪个布局为0,哪个布局为1?

时间:2012-11-09 19:58:44

标签: java android listview

我覆盖了项目中的getItemViewType()方法,以指明哪个视图用于列表中的项目,R.layout.listview_item_product_completeR.layout.listview_item_product_inprocess

我知道这个函数必须返回一个介于0和1之间的值,该值小于可能的视图数,在我的情况下为0或1。

我如何知道哪个布局为0,哪个布局为1?我假设我创建的第一个布局是0而后者是1,但我想返回一个变量,以便这个值灵活...

@Override
public int getItemViewType(int position) {
    // Define a way to determine which layout to use
    if(//test for inprocess){ 
        return INPROCESS_TYPE_INDEX;
    } else { 
        return COMPLETE_TYPE_INDEX;
    }
}

我可以参考哪些/在哪里定义COMPLETE_TYPE_INDEXINPROCESS_TYPE_INDEX的值?

2 个答案:

答案 0 :(得分:2)

  

我需要知道如何将COMPLETE_TYPE_INDEX定义为1或0.看起来像这样一件小事!

老实说,COMPLETE_TYPE_INDEX是0还是INPROCESS_TYPE_INDEX是1并不重要,反之亦然。但是你将它们定义为类变量,在这种情况下它们也可以是staticfinal

public class MyAdapter ... {
    private static final int COMPLETE_TYPE_INDEX = 0;
    private static final int INPROCESS_TYPE_INDEX = 1;
    private static final int NUMBER_OF_LAYOUTS = 2;

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            if(getItemViewType(position) == COMPLETE_TYPE_INDEX)
                convertView = mInflater.inflate(R.layout.listview_item_product_complete, null);
            else // must be INPROCESS_TYPE_INDEX
                convertView = mInflater.inflate(R.layout.listview_item_product_inprocess, null);

            // etc, etc...
            // Depending on what is different in your layouts, 
            //   you may need update your ViewHolder and more of getView()
        }

        // Load data that changes on each row, might need to check index type here too
    }
    @Override
    public int getItemViewType(int position) {
        Order thisOrder = (Order) myOrders.getOrderList().get(position);

        if(thisOrder.getOrderStatus().equals("Complete")) return COMPLETE_TYPE_INDEX;
        else return INCOMPLETE_TYPE_INDEX;
    }
    @Override
    public int getViewTypeCount() {
        return NUMBER_OF_LAYOUTS;
    }
}

答案 1 :(得分:1)

您的getView方法

中的

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

 if(getItemViewType(position) == INPROCESS_TYPE_INDEX){

//inflate a layout file
convertView = inflater.inflate(R.layout.R.layout.listview_item_product_inprocess);
}

else{
{

//inflate a layout file
convertView = inflater.inflate(R.layout.listview_item_product_complete);

}

return convertView;