1.自定義listview,首先在activity.xml中插入一個listview,可以用android:divider=“”設置分割線顏色樣式,android:dividerHeight=""設置分割線高度。 2.新建viewholder_item.xml設計每行Item顯示的樣式佈局。 3.自 ...
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);
}
}