Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> listview的ViewHolder優化,listviewviewholder

listview的ViewHolder優化,listviewviewholder

編輯:關於android開發

listview的ViewHolder優化,listviewviewholder


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);

}


}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved