0
 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,我正在尝试用不同颜色的元素制作一个列表。我已经制作了这个自定义适配器。为了确保它有效,我只是想让前两个项目具有不同的颜色,但文本始终设置为蓝色。

4

1 回答 1

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

于 2013-06-09T15:52:17.130 回答