BaseAdapter主要是为ListView提供数据源的,getView()返回的是每一行的view,我们可以在这个方法中加载自己设定的每一行的布局。下面用一个例子来说明如何使用BaseAdapter。
MainActivity.java
package com.example.baseadpaterdemos;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private List<Person> persons;
private ListView lists;
private EditText editText1;
private Button button;
private BaseAdapter adapter = null;
private final static int CONTEXT_MENU_EDIT = 0;
private final static int CONTEXT_MENU_SHARE = 1;
private final static int CONTEXT_MENU_DELETE = 2;
private final static int CONTEXT_MENU_CANCEL =3;
private MenuEntity[] contextMenus = {
new MenuEntity(0, CONTEXT_MENU_EDIT, 0, "编辑"),
new MenuEntity(0, CONTEXT_MENU_SHARE, 0, "共享"),
new MenuEntity(0, CONTEXT_MENU_DELETE, 0, "删除"),
new MenuEntity(0, CONTEXT_MENU_CANCEL, 0, "取消")
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.person_settings);
lists = (ListView)findViewById(R.id.listview);
editText1 = (EditText)findViewById(R.id.edit_text1);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
for(int i = 0; i < persons.size();i++){
persons.get(i).name = editText1.getText().toString();
}
adapter.notifyDataSetChanged();
}
});
initListAllPersons();
showByMyBaseAdapter();
initListViewEvent();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void initListAllPersons(){
persons = new ArrayList<Person>();
persons.add(new Person(100, "李小龙", "香港", android.R.drawable.ic_menu_gallery));
persons.add(new Person(101,"施瓦辛格","美国",android.R.drawable.ic_dialog_alert));
persons.add(new Person(102,"戴安娜王妃","英国",android.R.drawable.ic_dialog_dialer));
persons.add(new Person(103,"成龙","香港",android.R.drawable.ic_dialog_map));
persons.add(new Person(104,"史泰龙","美国",android.R.drawable.ic_lock_idle_alarm));
persons.add(new Person(105,"圣女贞德","法国",android.R.drawable.ic_media_next));
persons.add(new Person(106,"列宁","苏联",android.R.drawable.ic_media_play));
persons.add(new Person(107,"爱迪生","美国",android.R.drawable.ic_menu_add));
persons.add(new Person(108,"孔子","中国",android.R.drawable.ic_media_rew));
persons.add(new Person(109,"杨七郎","宋朝",android.R.drawable.ic_menu_zoom));
persons.add(new Person(110,"秦始皇","秦国",android.R.drawable.ic_menu_agenda));
persons.add(new Person(111,"岳飞","宋朝",android.R.drawable.ic_lock_lock));
persons.add(new Person(100, "李小龙", "香港", android.R.drawable.ic_menu_gallery));
persons.add(new Person(101,"施瓦辛格","美国",android.R.drawable.ic_dialog_alert));
persons.add(new Person(102,"戴安娜王妃","英国",android.R.drawable.ic_dialog_dialer));
persons.add(new Person(103,"成龙","香港",android.R.drawable.ic_dialog_map));
persons.add(new Person(104,"史泰龙","美国",android.R.drawable.ic_lock_idle_alarm));
persons.add(new Person(105,"圣女贞德","法国",android.R.drawable.ic_media_next));
persons.add(new Person(106,"列宁","苏联",android.R.drawable.ic_media_play));
persons.add(new Person(107,"爱迪生","美国",android.R.drawable.ic_menu_add));
persons.add(new Person(108,"孔子","中国",android.R.drawable.ic_media_rew));
persons.add(new Person(109,"杨七郎","宋朝",android.R.drawable.ic_menu_zoom));
persons.add(new Person(110,"秦始皇","秦国",android.R.drawable.ic_menu_agenda));
persons.add(new Person(111,"岳飞","宋朝",android.R.drawable.ic_lock_lock));
}
private void showByMyBaseAdapter(){
adapter = new MyBaseAdapter(this, persons);
lists.setAdapter(adapter);
}
public void initListViewEvent(){
//register a callback to be invoked when an item in this AdapterView has been clicked
lists.setOnItemClickListener(new OnItemClickListener() {
/*
* parent -- 发生Click事件所在的AdapterView
* view --AdapterView中被点击的那个view
* position--被点击的view的位置
* id --点击的view项的行号
* */
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "[onItemClickListener]Click: " + persons.get(position).name,
Toast.LENGTH_SHORT).show();
}
});
lists.setOnItemLongClickListener(new OnItemLongClickListener(){
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "[onItemLongClickListener]Click: " + persons.get(position).name,
Toast.LENGTH_SHORT).show();
return false;
}
});
lists.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"[OnItemSelectedListener:onItemSelected]点击了:"+ persons.get(position).name,
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"[OnItemSelectedListener:onNothingSelected]点击了",
Toast.LENGTH_SHORT).show();
}
});
//ListView组件:创建上下文菜单
lists.setOnCreateContextMenuListener(new OnCreateContextMenuListener(){
/*
* abstract
* void onCreateContextMenu(
* ContextMenu menu, //正在创建的context menu
* View v, //The view for which the context menu is being built
* //menuInfo--Extra information about the item for which the context menu should be shown.
* //This information will vary depending on the class of v
* ContextMenu.ContextMenuInfo menuInfo
* )
* */
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
//获取上下文菜单点击的ListView的位置(position)属性
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
int position = info.position;
//设置上下文菜单标题
menu.setHeaderTitle(persons.get(position).name);
//设置上下文菜单栏目
MenuEntity menuEntity = null;
for(int i=0;i<contextMenus.length;i++){
menuEntity = contextMenus[i];
menu.add(menuEntity.getGroupId(),menuEntity.getItemId(),menuEntity.getOrder(),menuEntity.getTitle());
}
}
});
}
@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return super.onContextItemSelected(item);
}
class MyBaseAdapter extends BaseAdapter{
private List<Person> personList;
Context context;
public MyBaseAdapter(Context context,List<Person> persons){
Log.d(TAG,"MyBaseAdapter()");
this.personList = persons;
this.context = context;
}
@Override
public int getCount() {
Log.d(TAG,"getCount()");
// TODO Auto-generated method stub
return (personList==null)?0:personList.size();
}
@Override
public Object getItem(int arg0) {
Log.d(TAG,"getItem(),arg0 = " + arg0);
// TODO Auto-generated method stub
return personList.get(arg0);
}
@Override
public long getItemId(int arg0) {
Log.d(TAG,"getItemId(),arg0 = " + arg0);
// TODO Auto-generated method stub
return arg0;
}
class ViewHolder{
TextView item1;
TextView item2;
TextView item3;
ImageView imageView;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(TAG,"getView(), postion = " + position + ",conVertView = " + convertView + ", parent = " + parent);
// TODO Auto-generated method stub
final Person person = (Person)getItem(position);
ViewHolder viewHolder = null;
if(convertView == null){
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.person_info, null);
viewHolder = new ViewHolder();
viewHolder.item1 = (TextView)convertView.findViewById(R.id.person_number);
viewHolder.item2 = (TextView)convertView.findViewById(R.id.person_name);
viewHolder.item3 = (TextView)convertView.findViewById(R.id.person_country);
viewHolder.imageView = new ImageView(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
params.width = 50;
viewHolder.imageView.setLayoutParams(params);
((LinearLayout)convertView).addView(viewHolder.imageView,2);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder)convertView.getTag();
}
viewHolder.item2.setText(person.name);
viewHolder.item3.setText(person.address);
viewHolder.item1.setText(String.valueOf(person.personId));
viewHolder.imageView.setImageResource(person.photo);
return convertView;
}
}
}
MenuEntity.java
package com.example.baseadpaterdemos;
public class MenuEntity {
public MenuEntity(int groupId,int itemId,int order,CharSequence title){
this.groupId = groupId;
this.itemId = itemId;
this.order = order;
this.title = title;
}
/*组编号*/
private int groupId;
/*菜单编号*/
private int itemId;
/*显示顺序号*/
private int order;
/*菜单名称*/
private CharSequence title;
public int getGroupId(){
return groupId;
}
public int getItemId(){
return itemId;
}
public int getOrder(){
return order;
}
public CharSequence getTitle(){
return title;
}
public void setGroupId(int groupId){
this.groupId = groupId;
}
public void setItemId(int itemId){
this.itemId = itemId;
}
public void setOrder(int order){
this.order = order;
}
public void setTitle(CharSequence title){
this.title = title;
}
}
Person.java
package com.example.baseadpaterdemos;
public class Person {
public int personId;
public String name;
public String address;
public int photo;
public Person(int id,String name,String address,int photo){
this.personId = id;
this.name = name;
this.address = address;
this.photo = photo;
}
}
res/layout/person_info.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/person_number"
android:layout_width="50sp"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/person_name"
android:layout_width="110sp"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/person_country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
res/layout/person_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/edit_text1"
android:layout_width="110sp"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="修改名字"/>
</LinearLayout>
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>