Android 列表视图中的自定义适配器有很多 ifs

Custom Adapter in Android listview has many ifs

我有一个 listview 的适配器,它扩展了底座 ArrayAdapter。填充列表成员的整个逻辑都在 if 块中。因为只有 4 个字段,所以没什么大不了的。但是如果你有一个更复杂的 adapter 怎么办? 为此使用 ifs 是一个好习惯,还是应该实施更优雅的解决方案(性能方面)?

   if (promo != null) {

        if(!(promo.getItemType().equals(""))){
            holder.item1.setText("Item group :"+ promo.getItemType());
        }
        else if(!(promo.getItemCode().equals(""))){
            holder.item1.setText(promo.getItemCode());
        }

        else if(!(promo.getCustCode().equals(""))){
            holder.item1.setText(promo.getCustCode());
        }
        else if(!(promo.getCustType().equals(""))){
            holder.item1.setText("Clients from: "+ promo.getCustType());
        }

        //set ItemRelation
        if( !(promo.getItemType().equals("")) ){
            holder.item2.setText( promo.getItemCode() );

        }else if(promo.getItemType().equals("1")){
            holder.item2.setText("Group " + promo.getItemCode());

        }else{
            holder.item2.setText("All items");
        }

        if(promo.getPromoType().equals("1")){
            holder.item3.setText(promo.getPercent() + "%");
        }else{
            holder.item3.setText("Sum " + promo.getSalesPrice());
        }

由于您没有分享代码,不宜提供更优雅的解决方案。但是,使用复杂的适配器并不总是意味着您会遇到性能问题。它只需要遵循良好的实践,比如使用 ViewHolder 来帮助 listview 回收视图。

我不认为有什么特殊的技巧可以避免'ifs'但是使用多个 if 语句应该没有任何问题。但是如果你将在你的 if 块中使用某种重循环那么它会影响你的程序的性能