关于listview的baseadapter的convertView复用问题

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sinat_25136209/article/details/68958719

这个适配器应该是初学的时候用的最多的了吧
这里主要讲的四个方法getView中的convertView的复用

public View getView(int position, View convertView, ViewGroup parent) {
            View inView=null;
            if (convertView==null) {
                inView = View.inflate(getApplicationContext(), R.layout.item_pm, null);
            }else {
                inView=convertView;
            }
            //下面的不用管,但是fndviewbyid中只要写上View的返回值!!!
            ProcessInfo processInfo = mInfos.get(position);


            TextView textView = (TextView)inView. findViewById(R.id.tv_name);
            TextView textView2=(TextView)inView. findViewById(R.id.tv_mem);
            ImageView imageView=(ImageView)inView. findViewById(R.id.iv_icon);
            CheckBox checkBox=(CheckBox)inView. findViewById(R.id.cb_select);

            textView.setText(processInfo.name);
             textView2.setText("占用内存:"
                     + Formatter.formatFileSize(getApplicationContext(),
                     processInfo.MemSize));
                     // 图标....
                     imageView.setImageDrawable(processInfo.icon);
            return inView;
        }

以上是第一种写法,下面是第二种写法

public View getView(int position, View convertView, ViewGroup parent) {
            //注意这里的区别!!!!!,
            /**
            *这里没有让填充器等于另一个view对象,而是直接判断converview是不是为空,
            *其实结果都是一样的,上面是先弄了一view的变量,当convertView为空的时候
            *给这个view赋值,不为空的时候,让view的值等于这个convertView.其实这个写法和
            *上面的写法都是一样的!!
            *
            */

             if (convertView == null) {
             convertView = View.inflate(getApplicationContext(), R.layout.item_pm, null);
             }


             // 取出控件
             TextView tvName = (TextView)
             convertView.findViewById(R.id.tv_name);
             TextView tvMem = (TextView)
             convertView.findViewById(R.id.tv_mem);
             ImageView ivIcon = (ImageView) convertView
             .findViewById(R.id.iv_icon);
             CheckBox cbSelect = (CheckBox) convertView
             .findViewById(R.id.cb_select);
             // 赋值
             // ProcessInfo processInfo = mInfos.get(position);
             ProcessInfo processInfo = getItem(position);

             tvName.setText(processInfo.name);
             tvMem.setText("占用内存:"
             + Formatter.formatFileSize(getApplicationContext(),
             processInfo.MemSize));
             // 图标....
             ivIcon.setImageDrawable(processInfo.icon);
             return convertView;
             }

上面的两种写法都运行!!!

展开阅读全文

ListView 复用问题

09-08

package com.linen.medical.adapter;rnrnimport java.util.ArrayList;rnimport java.util.List;rnimport java.util.Map;rnrnimport com.linen.medical.R;rnimport com.linen.medical.utils.T;rnrnimport android.content.Context;rnimport android.graphics.Color;rnimport android.view.LayoutInflater;rnimport android.view.View;rnimport android.view.View.OnClickListener;rnimport android.view.ViewGroup;rnimport android.widget.BaseAdapter;rnimport android.widget.Button;rnimport android.widget.TextView;rnrnpublic class QueueTitle01Adapter extends BaseAdapter rn private List> list;rn private LayoutInflater mInflater;rn private Context mcontext;rn rn private List tv_list = new ArrayList();rn private TextView tv_btn;rnrn public QueueTitle01Adapter(Context context, List> list) rn mInflater = LayoutInflater.from(context);rn this.list = list;rn this.mcontext = context;rn rnrn @Overridern public int getCount() rn // TODO Auto-generated method stubrn return list.size();rn rnrn @Overridern public Object getItem(int position) rn // TODO Auto-generated method stubrn return null;rn rnrn @Overridern public long getItemId(int position) rn // TODO Auto-generated method stubrn return 0;rn rnrn @Overridern public View getView(int position, View convertView, ViewGroup parent) rn // TODO Auto-generated method stubrn ViewHolder holder;rn if (convertView == null) rn holder = new ViewHolder();rn convertView = mInflater.inflate(R.layout.queue_up_title01_item,rn null);rn holder.kebie = (TextView) convertViewrn .findViewById(R.id.tv_queue01_kebie);rn holder.bingrenxingming = (TextView) convertViewrn .findViewById(R.id.tv_queue01_bingrenxingming);rn holder.doctor = (TextView) convertViewrn .findViewById(R.id.tv_queue01_doctor);rn holder.time = (TextView) convertViewrn .findViewById(R.id.tv_queue01_jiuzhenshijian);rn holder.address = (TextView) convertViewrn .findViewById(R.id.tv_queue01_jiuzhendidian);rn rn rn rn holder.btnqueue01 = (TextView) convertViewrn .findViewById(R.id.btn_queue_shenqingpaidui);rn holder.btnqueue01 = tv_btn;rn convertView.setTag(holder);rnrn else rn holder = (ViewHolder) convertView.getTag();rn rn holder.kebie.setText(list.get(position).get("kebie").toString());rn holder.bingrenxingming.setText(list.get(position)rn .get("bingrenxingming").toString());rn holder.doctor.setText(list.get(position).get("doctor").toString());rn holder.time.setText(list.get(position).get("jiuzhentime").toString());rn holder.address.setText(list.get(position).get("jiuzhendidian")rn .toString());rn tv_list.add(holder.btnqueue01);rn holder.btnqueue01.setOnClickListener(new queueBtnLestener(position));rn rn// holder.btnqueue01.setOnClickListener(new OnClickListener() rn//rn// @Overridern// public void onClick(View v) rn// // TODO Auto-generated method stubrn// rn// switch (v.getId()) rn// case R.id.btn_queue_shenqingpaidui: rn// tv_btn.setBackgroundColor(Color.parseColor("#808080"));rn// tv_btn.setTextColor(Color.parseColor("#ffffff"));rn// T.show(mcontext, "申请排队btn"+position, 0);rn// break;rn//rn// rn//rn// rn// );rn return convertView;rn rnrn class queueBtnLestener implements OnClickListener rn int position;rnrn public queueBtnLestener(int pos) rn this.position = pos;rn rnrn @Overridern public void onClick(View v) rn // TODO Auto-generated method stubrn switch (v.getId()) rn case R.id.btn_queue_shenqingpaidui: rn rn// tv_list.get(position).setBackgroundColor(Color.parseColor("#808080"));rn// tv_list.get(position).setTextColor(Color.parseColor("#ffffff"));rn// rn// tv_btn.setBackgroundColor(Color.parseColor("#808080"));rn// tv_btn.setTextColor(Color.parseColor("#ffffff"));rn T.show(mcontext, "申请排队btn"+position, 0);rn break;rnrn rn rn rnrn public class ViewHolder rn TextView kebie;rn TextView bingrenxingming;rn TextView doctor;rn TextView time;rn TextView address;rn TextView btnqueue01;rn rnrn点击btnqueue01 ,改变其背景为灰色,点击一个会出现多个变灰色!!据说是listview的复用问题,, 大神们帮解决下,最好给代码!!!! 论坛

BaseAdapter显示ListView问题

05-08

运行的时候有如下提示rn[color=#FF0000]java.lang.RuntimeException: Unable to start activity ComponentInfocom.example.dailytimetracker/com.example.dailytimetracker.TimeSchedulerActivity: java.lang.NullPointerException[/color],最后跟到listView.setAdapter(timeTrackerAdapter);这一行,但是在前面加上 if (timeTrackerAdapter != null)以后还是会出现相同的问题,请问究竟是哪里出错了?谢谢rnrnTimeSchedulerActivity.javarnrn[code=java]rnrnpublic class TimeSchedulerActivity extends ActionBarActivity rnrn //TimeTrackerAdapter timeTrackerAdapter;rn rn @Overridern protected void onCreate(Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rn setContentView(R.layout.activity_time_scheduler);rnrn if (savedInstanceState == null) rn getSupportFragmentManager().beginTransaction()rn .add(R.id.container, new PlaceholderFragment())rn .commit();rn rn rn ListView listView = (ListView)findViewById(R.id.time_list);rn TimeTrackerAdapter timeTrackerAdapter = new TimeTrackerAdapter();rn listView.setAdapter(timeTrackerAdapter); // 这里出错了,程序直接退出rn rn ..............rnrn[/code]rnrnTimeTrackerAdapter.javarnrn[code=java]rnpublic class TimeTrackerAdapter extends BaseAdapter rnrn private ArrayList times = new ArrayList();rn rn public TimeTrackerAdapter() rn times.add(new TimeRecord("38:23", "Feeling good!"));rn times.add(new TimeRecord("49:01", "Tired. Needed some tea!"));rn times.add(new TimeRecord("29:42", "Exhausted!"));rn rn ....................rnrn[/code]rnrnTimeRecord.javarnrn[code=java]rnrnpublic class TimeRecord rn private String time;rn private String notes;rn rn public TimeRecord(String time, String notes)rn rn this.time = time;rn this.notes = notes;rn rn .............rnrn[/code]rn 论坛

ListView之于BaseAdapter

08-14

功能是:把手机上电话号码以列表+checkbox形式,在AlertDialog.Builder对象上显示出来,勾选后点确认完成.rn片段如下:需要加一个final boolean debug=true; ArrayList blocklist= new ArrayList();rn问题写在代码的注释里的,为1、2、3、4条。rn[code=java] final Cursor cursor_phone= getContentResolver().query(rn ContactsContract.CommonDataKinds.Phone.CONTENT_URI,rn null,null,null,null);rn if(debug)rn System.out.println(" cursor_phone set successfully");rn BaseAdapter baseadapter = new BaseAdapter()rn /**rn * 1. 这里加个if(debug) System.out.println("");会导致Syntax error on tokens,misplaced coonstructsrn * 等莫名其妙的句法问题。不知何解。rn * 2. getCount会在blockListV.setAdapter(baseadapter);之后重复回调约10次,不知为何。rn * */t.println(" BaseAdapter getCount:"+rn cursor_phone.getCount());rn return cursor_phone.getCount();rn rnrn @Overridern public Object getItem(int position) rn // TODO Auto-generated method stubrn return position;rn rnrn @Overridern public long getItemId(int position) rn // TODO Auto-generated method stubrn return position;rn rn /**rn * 3. getView也会在blockListV.setAdapter(baseadapter);之后重复回调约10次,不知为何。rn */rn @Overridern public View getView(int position, View convertView,rn ViewGroup parent) rn // TODO Auto-generated method stubrn if(debug)rn System.out.println(" BaseAdapter getView<"+position+">");rn CheckBox adptCheckBox= new CheckBox(BlockCall.this);rn if(cursor_phone.moveToPosition(position))rn String phone_number= cursor_phone.getString(cursor_phone.getColumnIndex(rn ContactsContract.CommonDataKinds.Phone.NUMBER));rn if(debug)rn System.out.println(" cursor_phone.getnumber:"+phone_numberrn +"<"+position+">");rn rn adptCheckBox.setText(phone_number);rn if(inBlockList(phone_number))rn adptCheckBox.setChecked(true);rn rn rn rn return adptCheckBox;rn rn ;rn if(debug)rn System.out.println(" just after BaseAdapter");rn View view = getLayoutInflater().inflate(R.layout.list_view, null);rn /**rn * ListView获取实例时activity stoprn * 问题在:layout的.xml文件把ListView弄错了rn */rn final ListView blockListV= (ListView)view.findViewById(R.id.base_adpt_checkbox);rn blockListV.setAdapter(baseadapter);rn if(debug)rn System.out.println(" block listview setadapter");rn new AlertDialog.Builder(BlockCall.this).setTitle(R.string.contacts_list)rn .setView(view).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() rn /**rn * 这里加个if(debug) System.out.println("");会导致Syntax error on tokens,misplaced coonstructsrn * 等莫名其妙的句法问题。不知何解。rn * */rn @Overridern public void onClick(DialogInterface dialog, int which) rn // TODO Auto-generated method stubrn if(debug)rn System.out.println(" DialogInterface, blocklist OnClick");rn blocklist.clear();rn if(debug)rn System.out.println(" blocklist cleared:"+blocklist+rn ";\n==blockListV.getCount():"+blockListV.getCount());rn /**rn * 4. 如果存在着空的电话号码,点击确认后,activity 会stop 掉。rn * 现象是:getCount=16,但for结构里只执行到0-13就stop了,14和15未执行rn * getChildAt(i)中的i与position错位,导致越界。但不知为何。rn * 详细是i=0时,获取的是position=2的号码;i=13时,得到的是position=15的号码rn */rn for(int i=0; i< blockListV.getCount(); i++)rn CheckBox blockChild=new CheckBox(BlockCall.this);rn blockChild=(CheckBox)blockListV.getChildAt(i);rn if(debug)rn System.out.println(" (blockChild["+i+"].getText():"+rn (blockChild).getText().toString()+rn " | isChecked:"+blockChild.isChecked());rn if(blockChild.isChecked())rn blocklist.add((blockChild).getText().toString());rn rn rn if(debug)rn System.out.println("blocklist, after added:"+blocklist);rn rn ).show();[/code] 论坛

baseAdapter listview不显示

03-31

[code=Java]rn private ArrayList> getData() rn try rn Document doc = Jsoup.connect("http://www.3dmgame.com/").timeout(30000).get();rn Elements et = doc.getElementsByAttributeValue("class", "newList").select("li").select("a");rn for(Element e : et)rn HashMap map = new HashMap();rn String text = e.text().replace(Jsoup.parse(" ").text(), " ");rn map.put("text", text); rn list.add(map);rn rn catch (IOException e) rn // TODO Auto-generated catch blockrn e.printStackTrace();rn rn return list; rn rn[/code]rn这段代码获得的数据,使用simpleAdapter的时候可以正确显示rn但是是用baseadapter的时候就不显示东西,也不提示错误rnbaseadapter如下:[code=Java]rnprivate class NewsAdapter extends BaseAdapterrnrn @Overridern public int getCount() rn // TODO Auto-generated method stubrn return getData().size();rn rnrn @Overridern public Object getItem(int arg0) rn // TODO Auto-generated method stubrn return null;rn rnrn @Overridern public long getItemId(int arg0) rn // TODO Auto-generated method stubrn return 0;rn rnrn @Overridern public View getView(int arg0, View arg1, ViewGroup arg2) rn // TODO Auto-generated method stubrn arg1 = LayoutInflater.from(getApplicationContext()).inflate(R.layout.newslist, null);rn TextView tv = (TextView)arg1.findViewById(R.id.textView1);rn ImageView iv = (ImageView)arg1.findViewById(R.id.imageView1);rn rn tv.setText(getData().get(arg0).get("text").toString());rn return arg1;rn rn rn rn[/code]rn但是把getData()写成这样rn[code=Java]rnprivate ArrayList> getData()rn list = new ArrayList>();rn HashMap map = new HashMap();rn for(int i = 0; i < 2; i++)rn map.put("text", "dfdfadf");rn map.put("text", "fdedaf");rn rn list.add(map);rn return list; rn rn[/code]rn这样用baseadapter就可以用了,为什么啊 论坛

没有更多推荐了,返回首页