五、本次要讲的是一个listview的进阶效果,主要实现的功能是,单击显示的item时,会显示出一个大图,以突出效果,即抽屉效果的ListView。效果如下所示:
其主要实现思路是:在getView的时候,动态修改布局,将选中的item添加新的View,这样就做到了点击的时候,与其他的item不同的效果。
代码如下:
public class MainActivity extends ListActivity { DrawListAdapter adapter; int[] imgs={R.drawable.image,R.drawable.packed,R.drawable.paste,R.drawable.text,R.drawable.delete}; String[] text={"第一抽屉","第二抽屉","第三抽屉","第四抽屉","第五抽屉"}; int currentItem=0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); adapter = new DrawListAdapter(this); //setListAdapter和getListView方法是ListActivity的方法,分别用于设置adapter和获得一个listview this.setListAdapter(adapter); this.getListView().setOnItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub currentItem=arg2; //notifyDataSetChanged()可以在修改适配器绑定的数组后,不用重新刷新Activity,通知Activity更新ListView adapter.notifyDataSetChanged(); } }); } public class DrawListAdapter extends BaseAdapter{ Activity activity; LayoutInflater inflater; public DrawListAdapter(Activity a){ activity=a; inflater=activity.getLayoutInflater(); } public int getCount() { // TODO Auto-generated method stub return imgs.length; } public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } public long getItemId(int position) { // TODO Auto-generated method stub return position; } public View getView(int position, View convertView, ViewGroup arg2) { // TODO Auto-generated method stub LinearLayout layout=new LinearLayout(activity); layout.setOrientation(LinearLayout.VERTICAL); layout.addView(addTitleView(position)); if(currentItem==position){ layout.addView(addCustomView(position)); } return layout; } //获取选中项的内容 private View addCustomView(int i) { // TODO Auto-generated method stub View view=new View(activity); ImageView iv=new ImageView(activity); //根据点击的position设置相应要显示的图片 switch (i) { case 0: iv.setImageResource(R.drawable.ic_launcher); view=iv; break; case 1: iv.setImageResource(R.drawable.ic_launcher); view=iv; break; case 2: iv.setImageResource(R.drawable.ic_launcher); view=iv; break; case 3: iv.setImageResource(R.drawable.ic_launcher); view=iv; break; case 4: iv.setImageResource(R.drawable.ic_launcher); view=iv; break; } return view; } //获取list的标题内容 private View addTitleView(int i) { // TODO Auto-generated method stub LinearLayout layout=new LinearLayout(activity); layout.setOrientation(LinearLayout.HORIZONTAL); ImageView iv=new ImageView(activity); iv.setImageResource(imgs[i]); layout.addView(iv,new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)); TextView tv=new TextView(activity); tv.setText(text[i]); layout.addView(tv,new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)); layout.setGravity(Gravity.CENTER); return layout; } } }