day4.06总结_Adapter自定义和优化和ListView

一、常见Adapter (构建adapter layout需要的item)

1.ArrayAdapter (数据集比较简单,可以是数组或list集合)

2.SimpleAdapter (数据集为List<? extends Map<String,?>>)

3.BaseAdapter(抽象类):自己写adapter可继承此类

4.SimpleCursorAdapter(数据集为一个Cursor对象)

5........

例子1:自定义adapter

MainActivity

public class MainActivity extends Activity implements OnItemClickListener {

         private List<News> list=new ArrayList<News>();

         @Override

         protected void onCreate(Bundle savedInstanceState) {

                   super.onCreate(savedInstanceState);

                   setContentView(R.layout.activity_main);

                   //1.获得ListView

                   ListView lsv=(ListView) findViewById(R.id.lsvId);

                   //2.构建adapter

                   NewsAdapter adapter=new NewsAdapter(this, R.layout.news_item_3, list);

                   //3.关联adapter

                   lsv.setAdapter(adapter);

                   //4.添加监听器

                   lsv.setOnItemClickListener(this);

                   //初始化数据(将来要启动工作线程去加载数据)

                   initData();

         }

         private void initData(){

                   File sdcard=

             new File("/mnt/sdcard");

                   File imgs[]=sdcard.listFiles(new FileFilter() {

                            @Override

                            public boolean accept(File file) {

                                     // TODO Auto-generated method stub

                                     return file.isFile()&&file.getName().endsWith(".png");

                            }

                   });

                   for(int i=0;i<imgs.length;i++){

                            News n=new News();

                            n.setTitle("title-"+i);

                            n.setContent("content-"+i);

                            Log.i("TAG", "imgs[i]="+imgs[i]);

                            n.setLogo(imgs[i].getPath());

                            n.setBirthday("2016-04-06");

                            list.add(n);

                   }

         }

         @Override

         public void onItemClick(AdapterView<?> parent, View view, int position,

                            long id) {

                   Object obj=parent.getItemAtPosition(position);   点击事件返回当前行(view

                   Log.i("TAG", "obj="+obj);

                   if(obj instanceof News){

                   News n=(News)obj;

                   //Toast.makeText(this,n.getContent(), 1).show();

                   //构建意图对象

                   Intent intent=new Intent(this,NewsActivity.class);   跳转到一个页面,并携带相应的

                   //封装要传递的数据(类似map,存储key/value)    参数

                   intent.putExtra("contentKey", n.getContent());

                   //将意图对象传给底层框架

                   startActivity(intent);

                   }

                   Log.i("TAG", "id="+id);

                   Log.i("TAG", "position="+position);

         }

}

NewsActivity

public class NewsActivity extends Activity {

 

         @Override

         protected void onCreate(Bundle savedInstanceState) {

                   super.onCreate(savedInstanceState);

                   setContentView(R.layout.activity_news);

                  //获得intent对象

                   Intent intent=getIntent();

                   String content=intent.getStringExtra("contentKey");

                   TextView tv=(TextView) findViewById(R.id.contentId);  

                   tv.setText(content);

         }

}

NewsAdapter

/**自定义适配器*/

public class NewsAdapter extends

    ArrayAdapter<News>{

         private int resource;

         //仿照arrayAdapter的构造方法

         public NewsAdapter(Context context,int resource,List<News> list) {

                   super(context,resource,list);

                   this.resource=resource;

         }

         /**构建adapter layout要显示的item(包饺子)

          * 每显示一个item都会调用一次此方法*/

         @Override

         public View getView(int position, View convertView, ViewGroup parent) {

                   //1.item layout对象(准备饺子皮对象)

                   //1)借助context找到resource id对应的xml资源

                   //2)借助xmlpullparser解析xml资源

                   //3)借助反射构建xml元素对象

                   //4)inflate方法的返回值为resource资源对应的根元素对象

                   View v=View.inflate(getContext(),resource,null);

                   //2.item data (饺子馅)

                   News news=getItem(position);

                   //3.set item data to item layout(将饺子馅放到饺子皮上包起来)

         //找到对应的view

                   ImageView img=(ImageView) v.findViewById(R.id.logo);

                   TextView titleTv=(TextView) v.findViewById(R.id.titleId);

                   TextView dateTv=(TextView) v.findViewById(R.id.dateId);

        //设置view

                   img.setImageURI(Uri.fromFile(new File(news.getLogo())));

                   titleTv.setText(news.getTitle());

                   dateTv.setText(news.getBirthday());

                   return v;//包好的饺子

         }

}

News

private String title;

         private String content;

         private String birthday;

         private String logo;

     …………

activity_main.xml:

android:id="@+id/lsvId"

activity_news.xml:

<TextView

        android:id="@+id/contentId"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textSize="20sp"

        />

news_item_3.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent" >

   

    <ImageView

        android:id="@+id/logo"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:src="@drawable/ic_launcher"

        />

    <TextView

        android:id="@+id/titleId"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_toRightOf="@id/logo"

        android:text="title"

        android:layout_marginTop="10dp"

        />

    <TextView

        android:id="@+id/dateId"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_toRightOf="@id/logo"

        android:layout_below="@id/titleId"

        android:text="2016-12-12"

        />

</RelativeLayout>

 

二、Adapter 优化

 

1.减少item view对象的构建次数(重用adapter对象

   中getView方法中的convertView对象)。

2.减少item view对象中子view的查找次数(

   减少getView方法内部findViewById方法的调用

   次数-借助viewHolder实现)

 

例子2:Adapter 优化

@Override

         public View getView(int position, View convertView, ViewGroup parent) {

                   Log.i("TAG", "convertView="+convertView);

                   //1.item layout对象(准备饺子皮对象)

                   //1)借助context找到resource id对应的xml资源

                   //2)借助xmlpullparser解析xml资源

                   //3)借助反射构建xml元素对象

                   //4)inflate方法的返回值为resource资源对应的根元素对象

                   View v=null;

                   ViewHolder vh=null;

                   if(convertView==null){//convertView (可重用的列表项对象)

                            v=View.inflate(context,resource,null);

                            vh=new ViewHolder();       牺牲空间,换取时间

                            vh.logo=(ImageView) v.findViewById(R.id.logo);

                            vh.titleTv=(TextView) v.findViewById(R.id.titleId);

                            vh.dateTv=(TextView) v.findViewById(R.id.dateId);

                            v.setTag(vh);//关联viewholder

                   }else{

                            v=convertView;

                            vh=(ViewHolder)convertView.getTag();

                   }

                   //2.item data (饺子馅)

                   News news=list.get(position);

                  

                   vh.logo.setImageURI(Uri.fromFile(new File(news.getLogo())));

                   vh.titleTv.setText(news.getTitle());

                   vh.dateTv.setText(news.getBirthday());

                   return v;//包好的饺子

         }

         /**每个item view对应一个viewHolder*/

         class ViewHolder{

                   ImageView logo;

                   TextView titleTv;

                   TextView dateTv;

         }

 

三、 Listview 其它?

1.Listview 的item中button元素的点击事件?

   在此应用中需要借助item view的android:descendantFocusability属性覆盖子元素事件,这样既可以点击listview的item,又可以点击item中的button元素。

例子3:两个按钮都可以使用和删除一行

MainActivity

public class MainActivity extends ListActivity {    继承ListActivity,默认使用ListView

         List<String> list=new ArrayList<String>();

         @Override

         protected void onCreate(Bundle savedInstanceState) {

                   super.onCreate(savedInstanceState);

                   //setContentView(R.layout.activity_main);

                   list.add("A");list.add("B");list.add("C");

                   //调用listactivity中的方法

                   Log.i("TAG","activity.onCreate");

                   setListAdapter(new ArrayAdapter<String>(this,R.layout.list_item_2,R.id.textView1,list){

                            @Override

                            public View getView(int position, View convertView, ViewGroup parent) {

                                     Log.i("TAG", "getView");

                                     View v=super.getView(position, convertView, parent);

                                     final ImageView btn=(ImageView)

                                     v.findViewById(R.id.button1);

                                     btn.setTag(position);

                                     btn.setOnClickListener(new OnClickListener() {

                                               @Override

                                               public void onClick(View v) {

                                                        Log.i("TAG", "onClick");

                                                        Log.i("TAG", "btn.getTag()="+btn.getTag());

                                                        //删除集合中数据

                                                        list.remove(((Integer)btn.getTag()).intValue());

                                                        //调用adapter的方法通知listview更新

                                                        notifyDataSetChanged();

                                               }

                                     });

                                     return v;

                            }

                   });

         }

         /**

          * 重写listactivity中的方法

          * 当点击listview中的item时会自动执行此方法*/

         @Override

         protected void onListItemClick(

         ListView l, View v, int position, long id) {

         String s=(String)

         l.getItemAtPosition(position);

         Toast.makeText(this, s, 1).show();

         }

}

list_item_2.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:descendantFocusability="blocksDescendants"   属性覆盖子元素事件

    android:layout_width="match_parent"

    android:layout_height="match_parent" >

activity_main.xml: 布局改成:ListView

 

 

2.ListView中item对象的选择?一般会在item对象中添加一个CheckedTextView

  或者用一个CheckBox.然后调用listview的setChoiceMode设置选择模式。

 

例子4:设置listview的选择模式并排序

MainActivity

public class MainActivity extends ListActivity {

 

         List<String> list=new ArrayList<String>();

         ArrayAdapter<String> adapter;

         @Override

         protected void onCreate(Bundle savedInstanceState) {

                   super.onCreate(savedInstanceState);

                   setContentView(R.layout.activity_main);

             list.add("B");list.add("A");list.add("D"); list.add("C");

             adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_checked,list);

             setListAdapter(adapter);

                   //设置listview的选择模式

                   //设置多选

                   //getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

                   //设置单选

                   getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

         }

         public void onClick(View v){

           Collections.sort(list);

           adapter.notifyDataSetChanged();   刷新,重新加载页面

         }

}

 

你可能感兴趣的:(day4.06总结_Adapter自定义和优化和ListView)