网上的书架有一个缺陷,就是在重写适配器的时候没有判断convertView==null,当你上下滚动控件时,内存会不断的猛增,当软件的内存超过50多M时会导致软件的崩溃,当你加上convertView==null时,当你上下滚动控件时,你会发现适配器里面的控件会乱跑。有什么问题大家都多提提意见,下面就是见证奇迹的时刻。
importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.view.Menu;
importandroid.widget.GridView;
publicclassMainActivityextendsActivity{
List<HashMap<String,String>>list=newArrayList<HashMap<String,String>>();
GridAdaptergrid=null;
GridViewview;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view=(GridView)findViewById(R.id.grid);
for(inti=0;i<52;i++){
HashMap<String,String>map=newHashMap<String,String>();
map.put("values",""+i);
list.add(map);
}
grid=newGridAdapter(MainActivity.this,list);
view.setAdapter(grid);
}
2、创建个GridAdapter.java
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importorg.goodev.squaregrid.R;
importorg.goodev.squaregrid.R.drawable;
importorg.goodev.squaregrid.R.id;
importorg.goodev.squaregrid.R.layout;
importandroid.content.Context;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.ViewGroup;
importandroid.widget.BaseAdapter;
importandroid.widget.ImageView;
importandroid.widget.LinearLayout;
importandroid.widget.TextView;
publicclassGridAdapterextendsBaseAdapter{
List<HashMap<String,String>>list=newArrayList<HashMap<String,String>>();
LayoutInflaterlayoutinflater;
privateContextmContext;
publicGridAdapter(Contextcontext,List<HashMap<String,String>>data){
list=data;
mContext=context;
}
publicintgetCount(){
returnlist.size();
}
@Override
publicObjectgetItem(intposition){
returnposition;
}
@Override
publiclonggetItemId(intposition){
returnposition;
}
@Override
publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
ViewHolderviewHolder;
if(convertView==null)
{
convertView=layoutinflater.from(mContext).inflate(R.layout.item,null);
viewHolder=newViewHolder();
viewHolder.linear=(LinearLayout)convertView.findViewById(R.id.LinearLayout_index1);
viewHolder.image=(ImageView)convertView.findViewById(R.id.icon);
convertView.setTag(viewHolder);
}else
{
viewHolder=(ViewHolder)convertView.getTag();
}
if(position%4==0){
viewHolder.linear.setBackgroundResource(R.drawable.left);
}elseif(position%4==3){
viewHolder.linear.setBackgroundResource(R.drawable.right);
}else{
viewHolder.linear.setBackgroundResource(R.drawable.center);
}
returnconvertView;
}
classViewHolder
{
publicLinearLayoutlinear;
publicImageViewimage;
}
}