getView()开关总是进入默认状态

时间:2013-06-09 15:47:24

标签: android

 public class Inventory extends ListActivity  {

private ArrayList<Item> inv = new ArrayList<Item>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.inventory);
    inv.add(new Item("Snake", 0, 50));
    inv.add(new Item("Snowball", 1, 200));
    inv.add(new Item("Stone", 4, 1000));

    setListAdapter(new ColorAdapter(this, R.layout.row, inv));
}


private class ColorAdapter extends ArrayAdapter<Item> {

    public ColorAdapter(Context context, int textViewResourceId, ArrayList<Item> inv) {
        super(context, textViewResourceId, inv);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);

        Item item = inv.get(position);

        TextView label = (TextView) view.findViewById(R.id.invrow);

        switch(position){
        case 0:
            label.setTextColor(Color.GRAY);
        case 1:
            label.setTextColor(Color.BLACK);
        default:
            label.setTextColor(Color.BLUE);
        }

        return view;
    }
}

我正在学习Android,我正在尝试使用不同颜色的元素制作列表。我已经制作了这个自定义适配器为了确保它有效,我只是想让前两个项目的颜色不同,但文本总是设置为蓝色。

1 个答案:

答案 0 :(得分:1)

将您的switch更改为:

switch(position) {
case 0:
    label.setTextColor(Color.GRAY);
    break;

case 1:
    label.setTextColor(Color.BLACK);
    break;

default:
    label.setTextColor(Color.BLUE);
}

否则它会遍历所有这些并以最后一个结束。 (http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html