隔行换色的Android ListView:使用BaseAdapter
package com.xsjayz.listview0822; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class ListViewActivity extends Activity { private String[] moreNames = null; private ListView listView = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // 在string中定义的字符串数组 moreNames = getResources().getStringArray(R.array.list_array); // 在main.xml中定义的listview listView = (ListView) findViewById(R.id.listViewMoreInfo); // 隐藏ListView的分隔线 listView.setDivider(null); listView.setAdapter(baseAdapter); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> view, View arg1, int position, long id) { switch (position) { case 0: toastUtil(ListViewActivity.this, position); break; case 1: toastUtil(ListViewActivity.this, position); break; case 2: toastUtil(ListViewActivity.this, position); break; case 3: toastUtil(ListViewActivity.this, position); break; case 4: toastUtil(ListViewActivity.this, position); break; case 5: toastUtil(ListViewActivity.this, position); break; case 6: toastUtil(ListViewActivity.this, position); break; } } }); } /** * 由于使用了大量的Toast,所以这里将这些Toast封装成一个方法 * * @param context * @param position */ public void toastUtil(Context context, int position) { Toast.makeText(context, moreNames[position], 3000).show(); } /** * 自定义BaseAdapter,返回隔行换色的视图显示在ListView上。 */ BaseAdapter baseAdapter = new BaseAdapter() { @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = null; TextView textView = null; // 获得布局文件more_info_my.xml,里面定义了TextView和ImageView两个组件 convertView = LayoutInflater.from(ListViewActivity.this).inflate( R.layout.more_info_my, null); textView = (TextView) convertView.findViewById(R.id.mytxt); imageView = (ImageView) convertView.findViewById(R.id.myimage); // 设置ListView显示的文字内容和图片 textView.setText(moreNames[position]); imageView.setImageResource(R.drawable.moreinfo_extend_next); // 为ListView设置隔行不同的背景颜色 if (position % 2 == 0) { convertView.setBackgroundDrawable(getResources().getDrawable( R.drawable.list_item_2)); } else { convertView.setBackgroundDrawable(getResources().getDrawable( R.drawable.list_item_1)); } // 返回的convertView对象将作为ListView的列表项 return convertView; } @Override public long getItemId(int position) { return 0; } @Override public Object getItem(int position) { return null; } @Override public int getCount() { return moreNames.length; } }; }