Android listView,自定义Adapter,另The constructor AlertDialog.Builder(MyAdapter) is undefined问题

来源:互联网 发布:iphone手机测评软件 编辑:程序博客网 时间:2024/06/06 00:58

        今天自学了Android listView的用法,为了在每一行列表中加button空间,需要自定义Adapter。下面是主要的过程。

        首先需要定义一个布局用于Adapter:如listlayout.xml。

        再定义一个MyAdapter类继承自BaseAdapter。

       在mainActivity中调用它:

               ListView list = (ListView) findViewById(R.id.ListView1); 
               MyAdapter adapter =new MyAdapter(this);  
               list.setAdapter(adapter);

               MyAdapter adapter =new MyAdapter(this);  

               list.setAdapter(adapter);

     具体的实现懒得说了,见上传的代码吧:

         http://download.csdn.net/detail/lxyxs/7520947

     运行效果图:

    

问题:    

另外遇到一个问题,在MyAdapter中我定义了Button的点击事件,用到了 AlertDialog。

      new AlertDialog.Builder(this)  

       .setTitle("listview")  

       .setMessage("第一个按钮")  

       .setPositiveButton("确定",new DialogInterface.OnClickListener() {  

           @Override  

           public void onClick(DialogInterface dialog,int which) {  

           }  

       })  

       .show();  

如果参数用this,是会报错的:

         The constructor AlertDialog.Builder(MyAdapter) is undefined

我理解的是这里用this其实是代表这个类,而MyAdapter并不是一个Activity,而我们是要在MainActivity这个Activity里用 AlertDialog。这是就要用到Context来联系了。注意到MainActivity里定义adapter的参数:

       MyAdapter adapter =new MyAdapter(this);  

这里的this就是MainActivity的context,那我们就可以在MyActivity中调用它。在MyAdapter类中定义:

       private Context context; 

然后构造函数中:

     public MyAdapter(Context context){  

this.context=context;

               this.mInflater = LayoutInflater.from(context);  

        mData=getData();

    } 

红色部分必须要

   最后使用 AlertDialog时:

            new AlertDialog.Builder(context)  

       .setTitle("listview")  

       .setMessage("第一个按钮")  

       .setPositiveButton("确定",new DialogInterface.OnClickListener() {  

           @Override  

           public void onClick(DialogInterface dialog,int which) {  

           }  

       })  

       .show();  

即把this换为context即可。

           



       


0 0