|
- package com.aliao.myandroiddemo.adapter;
-
- import android.content.Context;
- import android.util.Log;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.BaseAdapter;
- import android.widget.CheckBox;
- import android.widget.TextView;
-
- import com.aliao.myandroiddemo.R;
- import com.aliao.myandroiddemo.domain.BrandItemInfo;
-
- import java.util.List;
-
- /**
- * Created by liaolishuang on 14-3-31.
- */
- public class TestDisorderListAdapter extends BaseAdapter{
-
- private Context context;
- private List<BrandItemInfo> brandInfoList;
- private final String TAG = "disorderlist";
-
- public TestDisorderListAdapter(Context context, List<BrandItemInfo> list){
-
- this.context = context;
- brandInfoList = list;
-
- }
-
- @Override
- public int getCount() {
- return brandInfoList.size();
- }
-
- @Override
- public Object getItem(int i) {
- return null != brandInfoList?brandInfoList.get(i):null;
- }
-
- @Override
- public long getItemId(int i) {
- return i;
- }
-
- private class ViewHolder{
- private TextView brandEnNameTv;
- private TextView brandChNameTv;
- private CheckBox followCheckBox;
- }
-
- @Override
- public View getView(int i, View view, ViewGroup viewGroup) {
-
- ViewHolder viewHolder = null;
-
- if(null == view){
-
- LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- view = inflater.inflate(R.layout.item_testdisorderitem,null);
-
- viewHolder = new ViewHolder();
- viewHolder.brandChNameTv = (TextView) view.findViewById(R.id.item_chName_txt);
- viewHolder.brandEnNameTv= (TextView) view.findViewById(R.id.item_enName_txt);
-
- view.setTag(viewHolder);
-
- }else {
-
- viewHolder = (ViewHolder) view.getTag();
- }
-
- BrandItemInfo brandItemInfo = (BrandItemInfo) getItem(i);
- viewHolder.brandChNameTv.setText(brandItemInfo.getBrandChName());
- viewHolder.brandEnNameTv.setText(brandItemInfo.getBrandEnName());
-
- if(i < 3){
- view.setBackgroundColor(context.getResources().getColor(R.color.coupletwo));
- }
-
- return view;
- }
-
- }
为了设置品牌列表的前三项的背景色,在getView()方法中加入代码:- if(i < 3){
- view.setBackgroundColor(context.getResources().getColor(R.color.coupletwo));
- }
i是代表每一行的position,由0开始。当向上滑动列表时,i的值随着滑动行的改变而递增,没有任何问题,但是为什么只有i<3的情况才改变颜色,其他项还会有背景色的改变呢?
在Adapters and Holder Pattern部分我们已经了解了listview的缓存优化机制,滚出屏幕的视图会被缓存下来并被复用。我们以为只要设置i<3就可以让前3项变色,其他项自然就是背景色,却忽略了,除了前三项之外的某些行会去复用前三项的视图因此也就会有相同的背景色。所以当i>=3对应的某些行由于复用了i<3对应的行,造成了背景色也为砖红色。
解决方法就是必须对i不小于3的情况进行处理,把它设置为背景色即:
- if(i < 3){
- view.setBackgroundColor(context.getResources().getColor(R.color.coupletwo));
- }else{
- view.setBackgroundColor(context.getResources().getColor(R.color.background));
- }
|
|