listview的ViewHolder优化

手机开发 2016-11-19

1.自定义listview,首先在activity.xml中插入一个listview,可以用android:divider=“”设置分割线颜色样式,android:dividerheight=""设置分割线高度。

2.新建viewholder_item.xml设计每行Item显示的样式布局。

3.自定义Adapter(继承BaseAdapter),定义一个内部类ViewHolder,并将布局中的控件作为成员变量。如:

public final class ViewHolder{ public ImageView img; public TextView title; }

然后在getView()方法中通过视图缓存机制来重新以缓存。完整创建代码如下:

package com.example.listview;

import java.util.List;

import android.content.Context;

import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.TextView;

public class ViewHolderAdapter extends BaseAdapter { private List<String> mData; private LayoutInflater mInflater; public ViewHolderAdapter(Context context,List<String> data){ this.mData=data; mInflater=LayoutInflater.from(context); }

@Override public int getCount() { // TODO Auto-generated method stub return mData.size(); }

@Override public Object getItem(int position) { // TODO Auto-generated method stub return mData.get(position); }

@Override public long getItemId(int position) { // TODO Auto-generated method stub return position; }

@Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder=null; if(convertView==null){ holder=new ViewHolder(); convertView=mInflater.inflate(R.layout.viewholder_item,null);//填充自定义item holder.img=(ImageView)convertView.findViewById(R.id.imageView); holder.title=(TextView)convertView.findViewById(R.id.textView); convertView.setTag(holder); }else{ //通过Tag找到缓存的布局 holder=(ViewHolder)convertView.getTag(); } holder.img.setBackgroundResource(R.drawable.one); holder.title.setText(mData.get(position)); return convertView; } public final class ViewHolder{ public ImageView img; public TextView title; }

}

4.最后在MainActivity中显示。

package com.example.listview;

import java.util.ArrayList;

import java.util.List;

import android.app.Activity;import android.os.Bundle;

import android.widget.ListView;

public class MainActivity extends Activity { private List<String> mData; private ViewHolderAdapter adapter; private ListView listview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listview=(ListView) findViewById(R.id.listview); mData=new ArrayList<String>(); for(int i=0;i<120;i++){ mData.add(""+i); } adapter=new ViewHolderAdapter(this,mData); listview.setAdapter(adapter); }

}

相关推荐