public static class MyAdapter extends BaseAdapter { private LayoutInflater inflater; public MyAdapter(Context context) { inflater = LayoutInflater.from(context); } @Override public int getCount() { // TODO Auto-generated method stub return 10; } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { View view = inflater.inflate(R.layout.listview_layout, null); CheckBox check = (CheckBox) view.findViewById(R.id.check); Drawable d= inflater.getContext().getResources() .getDrawable(R.drawable.icon_item_small_selected); if (arg0 == 1) { d.setAlpha(255); } else { d.setAlpha(70); } check.setButtonDrawable(d); return view; } }
看起來非常的正常,只不過是在position為1的時候將透明度改成255其他時候為70
但是結果是如下面這張圖... 我們會發現position 1的透明度竟然不是255.....
這其實是因為當getdrawable取得同一張圖時其實是共用resource而且共用state ,
所以當你針對某一張圖做更改時,其實同時也改到了其他共用的view
那要怎麼解決? mutate
接著讓我們將原本的code 加入 mutate
@Override public View getView(int arg0, View arg1, ViewGroup arg2) { View view = inflater.inflate(R.layout.listview_layout, null); CheckBox check = (CheckBox) view.findViewById(R.id.check); Drawable d = inflater.getContext().getResources() .getDrawable(R.drawable.icon_item_small_selected); if (arg0 == 1) { d.mutate().setAlpha(255); } else { d.mutate().setAlpha(70); } check.setButtonDrawable(d); return view; }
讓我們再看一次結果
everything works.
沒有留言:
張貼留言