BaseAdapter中重写getview的心得以及发现convertView回收的机制

BaseAdapter中重写getview的心得以及发现convertView回收的机制

 845人阅读 评论(0) 收藏 举报

以前一直在用BaseAdapter,对于其中的getview方法的重写一直不太清楚。今天终于得以有空来探究它的详细机制。
下面先讲讲我遇到的几个问题:
一.View getview(int position, View convertview, ViewGroup parent )中的第二个参数是什么含义;
二.View的SetTag和getTag方法的用途;
先来解决第一个问题:
android SDK中这样讲参数 convertview :
the old view to reuse, if possible. 
Note: You should check that this view is non-null and of an appropriate type before using.

 If it is not possible to convert this view to display the correct data, this method can create a new view.
翻译:
如果可以的话,这是旧View(这里不便翻译有的人翻成视图)的重用。 建议:在用之前,你应该检查这个View是
不是非空,是不是一个合适的类型。
如果不可能让这个VIew去显示一个恰当的数据,这个方法会创建一个新的View。

如果我们要做的是一个ListView,在手机上显示的只有那么几条Item,而整个ListView可能有很长,可能是100条
甚至是上万条,总不能让这么多条Item都驻留在内存中,所以android为你准备了一套机制,就是Recycler(反复循
环器),他的具体工作原理可以到 http://www.cnblogs.com/xiaowenji/archive/2010/12/08/1900579.html去看。
但是有些地方他没有讲清,所以我再讲一下。先把代码贴出来
布局文件main.xml


[java] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.     <ListView  
  7.         android:id="@+id/result"  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="fill_parent"  
  10.         android:cacheColorHint="#00000000" >  
  11. </ListView>  
  12. </LinearLayout>  
此处注意ListView的android:layout_height属性值为"fill_paternt",如果为“wrap_content"将会是另一种情况

adapter的代码ListViewAdapter.java 

[java] view plaincopy
  1. class ListViewAdapter extends BaseAdapter  
  2.    {  
  3.         private Context mContext;  
  4.         int i=0;  
  5.         public ListViewAdapter (Context context)<span style="white-space:pre">      </span>  
  6.         {  
  7.             this.mContext=context;  
  8.         }  
  9.     @Override  
  10.     public int getCount()  
  11.     {  
  12.         return 30;  
  13.               
  14.     }  
  15.     @Override  
  16.     public Object getItem(int position)  
  17.     {  
  18.     <span style="white-space: pre; ">   </span>return position;  
  19.     }  
  20.     @Override  
  21.     public long getItemId(int position)  
  22.     {  
  23. <span style="white-space: pre; ">       </span>return 0;  
  24.     }  
  25. <span style="white-space: pre; ">   </span>@Override  
  26.     public View getView(int position, View convertView, ViewGroup parent)  
  27.     {  
  28.     <span style="white-space: pre; ">   </span>System.out.println("getView " + position + " " + convertView);//调试语句  
  29.     <span style="white-space: pre; ">   </span>Holder holder;  
  30.         if(null==convertView)  
  31.         {  
  32.             holder=new Holder();  
  33.             convertView=LayoutInflater.from(mContext).inflate(R.layout.textview, null); //mContext指的是调用的Activtty  
  34.             holder.textView=(TextView)convertView.findViewById(R.id.textview);  
  35.             convertView.setTag(holder);  
  36.         }  
  37.         else  
  38.         {  
  39.             holder=(Holder)convertView.getTag();  
  40.         }  
  41.         holder.textView.setText("position: "+position);  
  42.             return convertView;           
  43.     }  
  44.     class Holder  
  45.     {  
  46.         public TextView textView;  
  47.   
  48.     }  
  49.     }  

运行程序之后发现屏幕上显示出的Item的convertview都为空,向下滑动新产生的Item的convetview都不为空。到此为止和上面链接中讲的是一致的,但是如果设置ListView的android:layout_height属性值为“wrap_content

之后,发现只有第一个Item的convertview为null其他的不为空。

虽然两种设置不同,结果也不同,但是convertview的机制没有变。

其实到此为止我们可以总结出convertview的机制了,就是在初始显示的时候,每次显示一个item都调用一次getview方法但是每次调用的时候covertview为空(因为还没有旧的view),当显示完了之后。如果屏幕移动了之后,并且导致有些Item(也可以说是view)跑到屏幕外面,此时如果还有新的item需要产生,则这些item显示时调用的getview方法中的convertview参数就不是null,而是那些移出屏幕的view(旧view),我们所要做的就是将需要显示的item填充到这些回收的view(旧view)中去,最后注意convertview为null的不仅仅是初始显示的那些item,还有一些是已经开始移入屏幕但是还没有view被回收的那些item。

最终我们用亲手写的代码实现了Recycler(反复循环器).


第二个问题其实应该在第一个问题中嵌套来讲,但是为了思路清晰我分开了:

view的setTag和getTag方法其实很简单,在实际编写代码的时候一个view不仅仅是为了显示一些字符串、图片,有时我们还需要他们携带一些其他的数据以便我们对该view的识别或者其他操作。于是android 的设计者们就创造了setTag(Object)方法来存放一些数据和view绑定,我们可以理解为这个是view 的标签也可以理解为view 作为一个容器存放了一些数据。而这些数据我们也可以通过getTag() 方法来取出来。

到这里setTag和getTag大家应该已经明白了。再回到上面的话题,我们通过convertview的setTag方法和getTag方法来将我们要显示的数据来绑定在convertview上。如果convertview 是第一次展示我们就创建新的Holder对象与之绑定,并在最后通过return convertview 返回,去显示;如果convertview 是回收来的那么我们就不必创建新的holder对象,只需要把原来的绑定的holder取出加上新的数据就行了。


至此我的问题讲完了,你的问题解决了么?


展开阅读全文

BaseAdaptergetview问题

07-11

public class MyAdapter extends BaseAdapter rnrn private LayoutInflater mlayInflater;rnrn public MyAdapter(Context context,rn ArrayList> listItem) rn // TODO Auto-generated constructor stubrn this.mlayInflater = LayoutInflater.from(context);rn rnrn @Overridern public int getCount() rn // TODO Auto-generated method stubrn return listItem.size();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 rnrn @Overridern public View getView(final int position, View convertView, ViewGroup parent) rn // TODO Auto-generated method stubrn if (convertView == null) rn convertView = getLayoutInflater().inflate(R.layout.list_views,rn null);rn rn TextView arriveStationName = (TextView) convertViewrn .findViewById(R.id.ZC_sesatList_stationName);rn TextView ticketType = (TextView) convertViewrn .findViewById(R.id.ZC_sesatList_ticketType);rn TextView seatType = (TextView) convertViewrn .findViewById(R.id.ZC_sesatList_seatType);rn TextView flag = (TextView) convertViewrn .findViewById(R.id.ZC_sesatList_flag);rn // 根据list的值设置rn Map dataListMap = (Map) listItemrn .get(position);rn String ZC_arriveStationName = dataListMap.get("arriveStationName").toString();rn String ZC_ticketType = dataListMap.get("ticketType").toString();rn String ZC_seatType = dataListMap.get("seatType").toString();rn String ZC_flag = dataListMap.get("flag").toString();rn if(ZC_flag.equals(""))rn arriveStationName.setTextColor(Color.RED);rn ticketType.setTextColor(Color.RED);rn seatType.setTextColor(Color.RED);rn flag.setTextColor(Color.RED);rn rn arriveStationName.setText(ZC_arriveStationName);rn ticketType.setText(ZC_ticketType);rn seatType.setText(ZC_seatType);rn flag.setText(ZC_flag);rnrn // 点击跳转事件rn list.setOnItemClickListener(new OnItemClickListener() rnrn @Overridern public void onItemClick(AdapterView arg0, View arg1, int arg2,rn long arg3) rn // TODO Auto-generated method stubrn Map map = (Map) listItem.get(arg2);rn String seatNo = map.get("seatNo").toString();rn String coachNo = map.get("coachNo").toString();rn String limit_stationName = map.get("limit_stationName")rn .toString();rn String board_stationName = map.get("board_stationName")rn .toString();rn String arriveStationName = map.get("arriveStationName")rn .toString();rn String ticketType = map.get("ticketType").toString();rn String seatTypeNo = map.get("seatTypeNo").toString();rn String seatType = map.get("seatType").toString();rn String flag = map.get("flag").toString();rn Intent intent = new Intent(rn zc_xiweiguanli_chexiang_seatlist.this,rn zc_xiweiguanli_chexiang_seatDetails.class);rn intent.putExtra("seatNo", seatNo);rn intent.putExtra("coachNo", coachNo);rn intent.putExtra("limit_stationName", limit_stationName);rn intent.putExtra("board_stationName", board_stationName);rn intent.putExtra("arriveStationName", arriveStationName);rn intent.putExtra("ticketType", ticketType);rn intent.putExtra("seatTypeNo", seatTypeNo);rn intent.putExtra("seatType", seatType);rn intent.putExtra("flag", flag);rn startActivity(intent);rn zc_xiweiguanli_chexiang_seatlist.this.finish();rn rnrn );rn return convertView;rn rn rnrn反复调用getview而且数据超过100就会空指针....颜色放置后发现所有的都变成红色了 论坛

BaseAdaptergetView问题

12-13

getView的代码如下:rn[code=Java] public View getView(int position, View convertView, ViewGroup parent) rn Log.i(TAG, "getView -- " + position + " -- " + convertView);rn rn ViewHolder holder = null;rn if(convertView == null)rn convertView = mInflater.inflate(R.layout.list_item, null);rn holder = new ViewHolder();rn holder.ivPic = (ImageView) convertView.findViewById(R.id.iv_pic);rn holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);rn holder.cbSelect = (CheckBox) convertView.findViewById(R.id.cb_selected);rn holder.btOk = (Button) convertView.findViewById(R.id.btn_ok);rn rn convertView.setTag(holder);rn elsern holder = (ViewHolder) convertView.getTag();rn rn rn convertView.setOnClickListener(new OnClickListener() rn rn public void onClick(View v) rn// viewHolder.cbSelect.toggle();rn Log.i(TAG, "click the convertView at ");rn rn );rn rn holder.btOk.setOnClickListener(new OnClickListener() rn rn public void onClick(View v) rn Log.i(TAG, "click the button");rn rn );rn rn holder.ivPic.setBackgroundResource(list.get(position).getPicId());rn holder.tvTitle.setText(list.get(position).getTitle());rn rn return convertView;rn [/code]rnrn我用的是模拟器,一屏显示了10个Item。rn但是在logcat中查看日志,0--9 的视图getView方法被调用了三遍,listView加载完成后我不进行任何滑动rn日志内容如下:rnAndroidRuntime(577): NOTE: attach of thread 'Binder Thread #3' failedrngetView -- 0 -- nullrngetView -- 1 -- android.widget.LinearLayout@40524048rngetView -- 2 -- android.widget.LinearLayout@40524048rngetView -- 3 -- android.widget.LinearLayout@40524048rngetView -- 4 -- android.widget.LinearLayout@40524048rngetView -- 5 -- android.widget.LinearLayout@40524048rngetView -- 6 -- android.widget.LinearLayout@40524048rngetView -- 7 -- android.widget.LinearLayout@40524048rngetView -- 8 -- android.widget.LinearLayout@40524048rngetView -- 9 -- android.widget.LinearLayout@40524048rngetView -- 0 -- android.widget.LinearLayout@40524048rngetView -- 1 -- nullrngetView -- 2 -- nullrngetView -- 3 -- nullrngetView -- 4 -- nullrngetView -- 5 -- nullrngetView -- 6 -- nullrngetView -- 7 -- nullrngetView -- 8 -- nullrngetView -- 9 -- nullrngetView -- 0 -- nullrngetView -- 1 -- android.widget.LinearLayout@4054b938rngetView -- 2 -- android.widget.LinearLayout@4054b938rngetView -- 3 -- android.widget.LinearLayout@4054b938rngetView -- 4 -- android.widget.LinearLayout@4054b938rngetView -- 5 -- android.widget.LinearLayout@4054b938rngetView -- 6 -- android.widget.LinearLayout@4054b938rngetView -- 7 -- android.widget.LinearLayout@4054b938rngetView -- 8 -- android.widget.LinearLayout@4054b938rngetView -- 9 -- android.widget.LinearLayout@4054b938rnDisplayed com.lxy/.AppMainActivity: +1s282msrnrn应该只加载1--9一次,并且convertView是null才对吧,我没有滑动过。这是为什么呢? 论坛

重写BaseAdapter的时候出现问题了

03-25

[code=java]package com.example.baseadapter;rnrnimport android.R.raw;rnimport android.view.LayoutInflater;rnimport android.view.View;rnimport android.view.ViewGroup;rnimport android.widget.BaseAdapter;rnimport android.widget.EditText;rnimport android.widget.TextView;rnrnpublic class mybadapter extends BaseAdapter rn LayoutInflater inflate;rn @Overridern public int getCount() rn // TODO Auto-generated method stubrn return 10;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 ViewHolder holder=null;rn if (convertView == null) rn convertView = inflate.inflate(R.layout.list, null); //<--35行在这rn holder=new ViewHolder();rn holder.tView=(TextView) convertView.findViewById(R.id.tv);rn holder.editText=(EditText) convertView.findViewById(R.id.et);rn convertView.setTag(holder);rn holder.editText.setTag(position);rn else rn holder=(ViewHolder) convertView.getTag();rn convertView.setTag(holder);rn rn holder.tView.setText("测试:" + position);rn holder.editText.setText("测试:" + position);rn return convertView;rn rn final static class ViewHolderrn TextView tView;rn EditText editText;rn rnrn[/code]rnrnrn[code=text]03-25 08:39:43.351: E/Trace(8121): error opening trace file: No such file or directory (2)rn03-25 08:39:45.818: E/AndroidRuntime(8121): FATAL EXCEPTION: mainrn03-25 08:39:45.818: E/AndroidRuntime(8121): java.lang.NullPointerExceptionrn03-25 08:39:45.818: E/AndroidRuntime(8121): at com.example.baseadapter.mybadapter.getView(mybadapter.java:35)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.widget.AbsListView.obtainView(AbsListView.java:2159)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.widget.ListView.measureHeightOfChildren(ListView.java:1246)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.widget.ListView.onMeasure(ListView.java:1158)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.View.measure(View.java:15518)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.View.measure(View.java:15518)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.View.measure(View.java:15518)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.View.measure(View.java:15518)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.View.measure(View.java:15518)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.Choreographer.doCallbacks(Choreographer.java:562)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.Choreographer.doFrame(Choreographer.java:532)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.os.Handler.handleCallback(Handler.java:725)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.os.Handler.dispatchMessage(Handler.java:92)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.os.Looper.loop(Looper.java:137)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at android.app.ActivityThread.main(ActivityThread.java:5041)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at java.lang.reflect.Method.invokeNative(Native Method)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at java.lang.reflect.Method.invoke(Method.java:511)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)rn03-25 08:39:45.818: E/AndroidRuntime(8121): at dalvik.system.NativeStart.main(Native Method)rn[/code]rnrn 论坛

继承ArrayAdapter,重写getView时,convertView setTag与holder里addTextChangedListener同时存在出错

07-13

写了一个用gridView弄的课程表,因为item要可编辑,所以item里就一个EditText;rn继承ArrayAdapter,ViewHolder只有EditText edit一个成员。rn下面是getView 部分内容rnViewHolder holder = null;rn if (convertView ==null)rn holder = new ViewHolder();rn LayoutInflater mInflater = LayoutInflater.from(context);rn convertView = mInflater.inflate(R.layout.grid_item, null);rn holder.edit = (EditText)convertView.findViewById(R.id.edit);rn holder.edit.setTag(position);rn class MyEditWatcher implements TextWatcherrn public MyEditWatcher(ViewHolder holder)rn mHolder = holder;rn rn private ViewHolder mHolder;rn public void afterTextChanged(Editable s) rn // TODO Auto-generated method stubrn int pos = (Integer)mHolder.edit.getTag();rn objects.set(pos, s.toString());rn rnrn public void beforeTextChanged(CharSequence s, int start,rn int count, int after) rn // TODO Auto-generated method stubrn rn rnrn public void onTextChanged(CharSequence s, int start,rn int before, int count) rn // TODO Auto-generated method stubrn rn rn rn rn holder.edit.addTextChangedListener(new MyEditWatcher(holder));rn convertView.setTag(holder);rn [color=#FF0000]holder.edit.setText(objects.get(position).toString());[/color]rn System.out.println("Suceed!");rn经过测试,是在红色字体部分出错的,问题应该是出在MyEditWatche上,求高手帮忙解决一下,谢谢! 论坛

安卓开发为何我点EditText会调用BaseAdaptergetView方法

01-02

public class MainActivity extends Activity nList list=new ArrayList();nString date;nListView lv=null;nMessageAdapter ma=null;n @Overriden protected void onCreate(Bundle savedInstanceState) n super.onCreate(savedInstanceState);n requestWindowFeature(Window.FEATURE_NO_TITLE);n setContentView(R.layout.activity_main);n lv=(ListView) findViewById(R.id.listView1);n list.add(new Msg(Type.Receive,"主人你好"));n ma=new MessageAdapter(this,list); n lv.setAdapter(ma);n n n n MessageAdapter类:n public class MessageAdapter extends BaseAdaptern private LayoutInflater mInflater;n private List mDatas;nn public MessageAdapter(Context context, List datas)n n mInflater = LayoutInflater.from(context);n mDatas = datas;n nn @Overriden public int getCount()n n return mDatas.size();n nn @Overriden public Object getItem(int position)n n return mDatas.get(position);n nn @Overriden public long getItemId(int position)n n return position;n nn /**n * 接受到消息为1,发送消息为0n */n @Overriden public int getItemViewType(int position)n n Msg msg = mDatas.get(position);n return msg.getType() == Type.Receive ? 1 : 0;n nn @Overriden public int getViewTypeCount()n n return 2;n nn @Overriden public View getView(int position, View convertView, ViewGroup parent)n n ViewHolder vh=null; n n Msg chatMessage = mDatas.get(position);n n if(convertView==null)n n vh=new ViewHolder();n if(chatMessage.getType()==Type.Receive)n convertView=mInflater.inflate(R.layout.left,parent, false);n vh.createDate=(TextView) convertView.findViewById(R.id.receiveDate);n vh.content=(TextView) convertView.findViewById(R.id.receiveContent);n n convertView.setTag(vh);n elsenn convertView=mInflater.inflate(R.layout.right,null);n vh.createDate=(TextView) convertView.findViewById(R.id.sendDate);n vh.content=(TextView) convertView.findViewById(R.id.sendContent);n convertView.setTag(vh);n n n elsen n vh=(ViewHolder) convertView.getTag(); n n n vh.createDate.setText(chatMessage.getContent());n vh.content.setText(chatMessage.getDateStr());n return convertView;n nn private class ViewHoldern n public TextView createDate;n public TextView content;n nnMsg类:npublic class Msg npublic String content,name,DateStr;nprivate Date date;npublic Type type;nenum Typen send,Receive;nnpublic Msg()n nnpublic Msg(Type type,String content)n super();n this.type=type;n this.content=content;n setDate(new Date());nnpublic String getContent()n return content;nnpublic Type getType()n return type;nnpublic String getDateStr()n return DateStr;nnpublic void setDate(Date date)n n this.date=date;n DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");n DateStr=df.format(date);nnpublic void setType(Type t)n this.type=t;nnpublic Date getDate()n return date;nnpublic void setMsg(String msg)n content=msg;nnn点击editText栏的时候就会调用getView方法,我找了好三四天了始终没有找到问题的根结,现在把所有java代码都贴上来了求帮我看看是哪里出的问题 问答

求助:自定义BaseAdapter调用了getCount()方法却没有执行getView()

01-22

[b][color=#FF0000]自定义BaseAdapter调用了getCount()方法却没有执行getView()方法,rn大致结构为:使用xutils框架开发,在MainActivity使用了FragmentTabHost布局;其中NewsFragment中使用了ViewPagerIndicatorView;在ViewPagerIndicatorView中放的是PullToRefreshListView;[/color]rn[/b]rn界面效果如下:rn[img=https://img-bbs.csdn.net/upload/201501/22/1421918174_675922.png][/img]rnrnrnNewsFragment.java代码如下:rnrnpublic class NewsFragment extends Fragment rn rn private Context context;rn rn @ViewInject(R.id.viewpager_indicator_view)rn private ViewPagerIndicatorView viewPagerIndicatorView;rn rn rn private PullToRefreshListView newTabHotListView;rn private NewsTabHotRequest request ;rn private NewsTabHotListAdapter adapter=null;rn private Dialog progressDialog; rn private boolean isSelect;rn private BaseBean bean = null;rn rn @Overridern public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) rn View view = inflater.inflate(R.layout.news_fragment, container, false);rn ViewUtils.inject(this, view);rn //设置标题rn Activity activity = (Activity)context;rn activity.setTitle(R.string.Mian_Tabhost_News);rn Log.i("INFO","执行了onCreateView,开始调用InitTabHostView");rn newTabHotListView = (PullToRefreshListView)LayoutInflater.from(context).inflate(R.layout.news_hot_pager, null).findViewById(R.id.new_tab_hot_list);rn rn isSelect = true;rn //初始化数据对象rn bean = new News();rn // 设置底部下拉刷新模式 setMode(Mode.BOTH)rn newTabHotListView.setMode(Mode.PULL_FROM_START);rn // 设置下来监听事件 rn newTabHotListView.setOnRefreshListener(new OnRefreshListener() rn @Override rn public void onRefresh(PullToRefreshBase refreshView) rn String label = DateUtils.formatDateTime(context, rn System.currentTimeMillis(), rn DateUtils.FORMAT_SHOW_TIME rn | DateUtils.FORMAT_SHOW_DATE rn | DateUtils.FORMAT_ABBREV_ALL);rn Log.i("INFO","执行了刷新.." + label);rn // 显示最后更新的时间 rn refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);rn //加载数据rn request.InitListData();rn rn );rn rn //自己写的回调函数,监听当前列表是否到了倒数第二个列表项 rn ScrollToLastCallBack newTabHotScrollToLastCallBack=new ScrollToLastCallBack() rn @Override rn public void onScrollToLast(Integer pos) rn // TODO Auto-generated method stub rn Toast.makeText(context, "到倒数第二个", Toast.LENGTH_SHORT).show(); rn rn ;rn rnrn //获取ListView 绑定适配器Adapterrn ListView actualListView = newTabHotListView.getRefreshableView();rn Log.i("INFO","ListView.getHeight:" + actualListView.getHeight());rn LogUtils.i("ListView.getHeight:" + actualListView.getHeight());rn adapter = new NewsTabHotListAdapter((MainActivity)context,bean.getListItems(),actualListView,);rn // 设置适配器 rn actualListView.setAdapter(adapter);rn rn //初始化加载数据rn request = new NewsTabHotRequest(context, bean,rn newTabHotListView, adapter, progressDialog, isSelect);rn request.InitListData();rn rnrn final Map map = new LinkedHashMap();rn map.put("热门", LayoutInflater.from(context).inflate(R.layout.news_hot_pager,null));rn map.put("军事", LayoutInflater.from(context).inflate(R.layout.news_army_pager, null));rn map.put("历史", LayoutInflater.from(context).inflate(R.layout.news_history_pager, null));rn this.viewPagerIndicatorView.setupLayout(map);rn rn return view;rn rn rn @Overridern public void onAttach(Activity activity) rn super.onAttach(activity);rn this.context = (MainActivity)activity;rn rn rnrnrnNewsTabHotListAdapter.java代码如下:rnrnrnpublic class NewsTabHotListAdapter extends BaseAdapterrnrn private LayoutInflater inflater;rn private ListView listView;rn private List newsItems=new ArrayList();rn rn private ScrollToLastCallBack mScrollToLastCallBack=null;rnrn public NewsTabHotListAdapter(Activity activity, List _newsItems,rn ListView listView,final ScrollToLastCallBack scrollToLastCallBack) rn this.listView = listView;rn inflater = activity.getLayoutInflater();rn newsItems=_newsItems;rn mScrollToLastCallBack=scrollToLastCallBack;rn rn rn public interface ScrollToLastCallBackrn rn public void onScrollToLast(Integer pos);rn rn rn @Overridern public int getCount() rn // TODO Auto-generated method stubrn return newsItems.size();rn rn @Overridern public Object getItem(int position) rn // TODO Auto-generated method stubrn if(position >= getCount())rn return null;rn rn return newsItems.get(position);rn rn @Overridern public long getItemId(int position) rn // TODO Auto-generated method stubrn return position;rn rn @Overridern public View getView(int position, View convertView, ViewGroup parent) rn if(convertView == null) rn convertView = inflater.inflate(R.layout.news_tabhot_listview_item, null);rn rn convertView.setTag(position);rn News news = (News) getItem(position);rn rn TextView titleView = (TextView) convertView.findViewById(R.id.news_tabhot_title);rn titleView.setText(news.getTitle());rn rn TextView createuserView = (TextView) convertView.findViewById(R.id.news_tabhot_createuser);rn createuserView.setText(news.getCreateusername());rn rn TextView createDateView = (TextView) convertView.findViewById(R.id.news_tabhot_createdate);rn createDateView.setText(news.getCreatedate());rn rn //判断当前列表所在位置,当到最后两项时就加载rn int end=listView.getLastVisiblePosition(); rn if(end>getCount()-3&&getCount()-1rnrnrn rn rnrnrnrn[b][color=#FF0000]其一,怀疑是:rn这一行对象获的问题,但是newTabHotListView对象不为空,强转也成功。rnrn其二:调用了getCount()方法却没有执行getView()rnrn其三,newTabHotListView.setOnRefreshListener 监听在PullToRefreshListView下拉的时候没有执行;[/color][/b]rnrnrn[b]rn[color=#0000FF]rnAndroid新手菜鸟,希望高手指点一二,在此谢过,不甚感激~~~~[/color][b][/b][/b]rnrnrnrn 论坛

问Gallery配合BaseAdapter,其它一切正常,就是无法执行getView(...)...

07-12

public class GalleryAdapter extends BaseAdapterrnrnrn public int getCount()rn rn return count;//这里调试count=1;rn rnrn public Object getItem(int position)rn rn return position;//这里调试position=1;rn rnrn public long getItemId(int position)rn rn return position;rn rnrn public View getView(int position, View convertView, ViewGroup parent)//http://www.eoeandroid.com/forum.php?mod=viewthread&tid=200168rn rn if(convertView == null)rn rn rnrnrn/////////////////////////////////////////////////////////////////////////////////////////////////////rnpublic class CGallery extends Galleryrnrn public CGallery(Context context, AttributeSet attrs)rn rn super(context, attrs);rn rn public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY)rn rn int keyCode;rn if (e2.getX() > e1.getX())//滚动到了最左边rn rn keyCode = KeyEvent.KEYCODE_DPAD_LEFT;rn rn else//滚动到了最右边rn rn keyCode = KeyEvent.KEYCODE_DPAD_RIGHT;rn rn onKeyDown(keyCode, null);rn return true;rn rnrnrn///////////////////////////////////////////////////////////////////////////////////////////////////////////rn执行如下代码:rnCGallery gr_parent=(CGallery)findViewById(R.id.gallery_parent);rnGalleryAdapter ad_parent= new GalleryAdapter(this,catalogListNames,0.5f);rngr_parent.setAdapter(ad_parent);rngr_parent.setSelection(0);rn如上执行代码后,一切正常在activity中,gallery可以显示出来,就是不能显示每个子项,rn还有不管怎么调试都无法执行到GalleryAdapter的getView去,为什么啊? 论坛

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