


下面是精简代码:
public class Main extends Activity {
private int[] mListImage={R.drawable.shebei,R.drawable.income,R.drawable.shiwu,R.drawable.jiaotong,
R.drawable.yiliao,R.drawable.yifu,R.drawable.yule,R.drawable.zawu};
private int[] mListColor=new int []{0xffffffff,0xffff0033,0xff66cccc,0xff3333cc,0xff66cc33,0xffffcc33,
0xffff9900,0xffcc6600};
EditText et_desc,et_money;
Button bt_cancel,bt_save,bt_sumup;
ListView lv_type,lv_all_bill;
View view;
MyListAdapterTwo myListAdapterTwo;
protected void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.main);
et_desc=(EditText)findViewById(R.id.et01);
et_money=(EditText)findViewById(R.id.et02);
bt_cancel=(Button)findViewById(R.id.button02);
bt_save=(Button)findViewById(R.id.button03);
bt_sumup=(Button)findViewById(R.id.button01);
lv_all_bill=(ListView)findViewById(R.id.lv02);
lv_type=(ListView)findViewById(R.id.lv01);
view=(View)findViewById(R.id.view01);
myListAdapterTwo=new MyListAdapterTwo(this);
lv_type.setAdapter(myListAdapterTwo);
lv_type.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int position,long id){
Toast.makeText(Main.this, "hi2", Toast.LENGTH_LONG).show();
}
});
}
public class MyListAdapterTwo extends BaseAdapter{
private Context mContext;
public MyListAdapterTwo(Context context) {
mContext = context;
}
public int getCount() {
return mListImage.length;
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView image = null;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.bill_info_lv01, null);
image = (ImageView) convertView.findViewById(R.id.iv);
}
Log.v("position", "pos="+position);
int colorPos = position % mListColor.length;
convertView.setBackgroundColor(mListColor[colorPos]);
Log.v("setcolor", "success");
image.setImageResource(mListImage[colorPos]);
Log.v("setimage","success");
return convertView;
}
}
}
------解决方案--------------------
错在getView方法中:
错误代码:
ImageView image = null;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.bill_info_lv01, null);
image = (ImageView) convertView.findViewById(R.id.iv);
}
建议代码1:
ImageView image = null;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.bill_info_lv01, null);
image = (ImageView) convertView.findViewById(R.id.iv);
convertView.setTag(image);
} else {
image = (ImageView) convertView.getTag();
}
建议代码2:
ViewHolder viewHolder = null;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.bill_info_lv01, null);
viewHolder.image = (ImageView) convertView.findViewById(R.id.iv);
convertView.setTag(viewHolder);