本文介绍了ListFragment未呈现和getView()的适配器不会被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我可以收集看来,这可能是因为未显示的ListView我,我已经验证getCount将返回一个值不为零,但我看不到我在做什么错。

一切负载和喜欢它的行为的工作,但从来没有出现的ListView,我把背景颜色上mixed.xml片段引用,它的存在,并采取了全屏,但是当我设置背景颜色在我的ListView它不出现,就好像它并不是在所有的渲染。

更奇,getView不会被调用在我的适配器,这是从我移植到片段经常活动的所有工作code。

我已经打过电话notifyDataSetChanged这并没有改变任何东西,调试显示适配器充满数据和getCount将确实返回一个准确的计数大于0。

感谢您的帮助,我卡住了。

项目是开放的,可以在这里但我还包括相关的code此处

这是ListFragment:

 公共类FragmentTopicView扩展ListFragment实现ShackGestureEvent {        私人的ArrayList< ShackPost>帖子;
        私人字符串storyID = NULL;        私人字符串ERRORTEXT =;
        私人整数当前是= 1;
        私人整数storyPages = 1;
        私人字符串loadStoryID = NULL;
        私人布尔threadLoaded = TRUE;
        私人Hashtable的<字符串,字符串> postCounts = NULL;
        私人AdapterLimerifficTopic TVA;        公共FragmentTopicView(){        }        @覆盖
        公共无效的onCreate(捆绑savedInstanceState){
                // TODO自动生成方法存根
                super.onCreate(savedInstanceState);                this.setRetainInstance(真);
        }        @覆盖
        公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,捆绑savedInstanceState){                返回inflater.inflate(R.layout.topics,NULL);
        }        @覆盖
        公共无效onActivityCreated(捆绑savedInstanceState){
                super.onActivityCreated(savedInstanceState);                最终ShackGestureListener听者= Helper.setGestureEnabledContentView(R.layout.topics,getActivity());
                如果(听众!= NULL){
                        listener.addListener(本);
                }                如果(savedInstanceState == NULL){
                        //获取主题列表
                        GetChattyAsyncTask健谈=新GetChattyAsyncTask(getActivity());
                        chatty.execute();
                }                ListView控件LV = getListView();
                lv.setOnScrollListener(新OnScrollListener(){                        @覆盖
                        公共无效onScroll(AbsListView观点,诠释firstVisibleItem,诠释visibleItemCount,诠释totalItemCount){                                //开始加载下一页
                                如果(threadLoaded&放大器;&放大器; firstVisibleItem + visibleItemCount&GT = totalItemCount&放大器;&放大器;当前第±1℃; = storyPages){                                        //获取主题列表
                                        当前是++;
                                        GetChattyAsyncTask健谈=新GetChattyAsyncTask(getActivity());
                                        chatty.execute();                                }
                        }                        @覆盖
                        公共无效onScrollStateChanged(AbsListView观点,诠释scrollState){                        }                });        }    类GetChattyAsyncTask扩展的AsyncTask<弦乐,太虚,太虚> {
                保护ProgressDialog对话框;
                受保护的语境℃;                公共GetChattyAsyncTask(上下文的背景下){
                        this.c =背景;
                }                @覆盖
                保护无效doInBackground(字符串... PARAMS){                        threadLoaded = FALSE;                        尝试{
                                最后一个共享preferences preFS = preferenceManager.getDefaultShared preferences(C);
                                最后弦乐feedURL = prefs.getString(shackFeedURL的getString(R.string.default_api));
                                最终URL网址;                                如果(loadStoryID!= NULL){
                                        如果(当前是大于1)
                                                URL =新的URL(feedURL +/+ loadStoryID + + currentPage.toString()+的.xml,);
                                        其他
                                                URL =新的URL(feedURL +/+ loadStoryID +的.xml);
                                }
                                其他{
                                        如果(当前是大于1)
                                                URL =新的URL(feedURL +/+ storyID + + currentPage.toString()+的.xml,);
                                        其他
                                                URL =新的URL(feedURL +/index.xml);
                                }                                //从一个SAXParserFactory的SAXParser的。
                                最终的SAXParserFactory SPF = SAXParserFactory.newInstance();
                                最终的SAXParser SP = spf.newSAXParser();                                //获取我们创建了SAXParser的的的XMLReader。
                                最终的XMLReader XR = sp.getXMLReader();
                                //创建一个新的ContentHandler,并将其应用到XML阅读器
                                SaxHandlerTopicView saxHandler =新SaxHandlerTopicView(C,主题);                                xr.setContentHandler(saxHandler);                                //解析从我们的URL的XML数据。
                                xr.parse(新的InputSource(HttpHelper.Htt prequestWithGzip(url.toString(),C)));                                //我们的ExampleHandler现在提供分析的数据给我们。
                                如果(职位== NULL){
                                        帖= saxHandler.GetParsedPosts();
                                }
                                其他{
                                        ArrayList的< ShackPost> newPosts = saxHandler.GetParsedPosts();
                                        newPosts.removeAll(职位);
                                        posts.addAll(posts.size(),newPosts);                                }                                storyID = saxHandler.getStoryID();                                storyPages = saxHandler.getStoryPageCount();                                如果(storyPages == 0)// XML对于只有故事返回0
                                                                                //一页
                                        storyPages = 1;                        }
                        赶上(例外前){
                                // TODO:实现错误处理                        }                        返回null;
                }                @覆盖
                在preExecute保护无效(){
                        super.on preExecute();                        如果(当前是== 1)
                                对话框= ProgressDialog.show(getActivity(),NULL,加载健谈,真实,真实);
                        其他
                                SetLoaderVisibility(View.VISIBLE);
                }                @覆盖
                保护无效onPostExecute(虚空结果){
                        super.onPostExecute(结果);                        ShowData();                        SetLoaderVisibility(View.GONE);                        尝试{
                                dialog.dismiss();
                        }
                        赶上(例外五){
                        }                }        }     私人无效ShowData(){                如果(帖子!= NULL){
                        哈希表<字符串,字符串> tempHash = NULL;                        最后一个共享preferences preFS = preferenceManager.getDefaultShared preferences(getActivity());
                        最后弦乐登录= prefs.getString(shackLogin,);
                        最终诠释fontSize的=的Integer.parseInt(prefs.getString(fontSize的,12));                        尝试{
                                postCounts = GetPostCache();
                        }
                        赶上(例外前){                        }
                        如果(postCounts!= NULL)
                                tempHash =新的Hashtable<字符串,字符串>(postCounts);                        如果(TVA == NULL){
                                TVA =新AdapterLimerifficTopic(getActivity(),R.layout.lime_topic_row,职位,登录,fontSize的,tempHash);
                                setListAdapter(TVA);
                        }
                        其他{
                                tva.SetPosts(职位);
                                tva.notifyDataSetChanged();
                        }                        最终的ListView LV = getListView();
                        lv.setOnCreateContextMenuListener(新OnCreateContextMenuListener(){
                                @覆盖
                                公共无效onCreateContextMenu(文本菜单菜单视图V,ContextMenu.ContextMenuInfo menuInfo){
                                        menu.setHeaderTitle(「购股权」);
                                        menu.add(0,1,0,复制发布网址到剪贴板);
                                        menu.add(0,2,0,手表主题);
                                        menu.add(0,3,0,线程过期吗?);
                                        menu.add(0,4,0,Shacker的健谈资料);
                                }
                        });                        //更新回复计数话题上市
                        尝试{
                                UpdatePostCache();                        }
                        赶上(例外五){                        }                }
                其他{
                        如果(errorText.length()大于0){                                尝试{
                                        新AlertDialog.Builder(getActivity())的setTitle(错误)setPositiveButton(OK,NULL).setMessage(ERRORTEXT).show();
                                }
                                赶上(例外前){
                                        //不能的原因之一创建该错误的警报
                                        // 或其他
                                        Log.e(ShackDroid,无法创建错误警报ActivityTopicView:468);
                                }
                        }
                }
                threadLoaded = TRUE;
        }}

下面是我的FragmentActivity:

 公共类FragmentActivityTopic扩展FragmentActivity {
        @覆盖
        保护无效的onCreate(捆绑ARG){
                // TODO自动生成方法存根
                super.onCreate(ARG);                的setContentView(R.layout.mixed);
        }
}

这是我使用的适配器,以上getView提到不会被调用:

 公共类AdapterLimerifficTopic延伸BaseAdapter {        //私有上下文的背景下;
        私人列表< ShackPost>题目列表;
        私人最终诠释rowResouceID;
        私人最终字符串shackLogin;
        私人最终字样的脸;
        私人最终诠释fontSize的;
        私人最终哈希表<字符串,字符串> postCache;
        私人最终字符串showAuthor;
        私人最终资源研究;
        私人INT totalNewPosts = 0;        LayoutInflater膨胀; // = LayoutInflater.from(背景);        公共AdapterLimerifficTopic(上下文的背景下,INT rowResouceID,列表与LT; ShackPost>题目列表,字符串shackLogin,INT fontSize的,哈希表<字符串,字符串> postCache){
                this.topicList =题目列表;
                this.rowResouceID = rowResouceID;
                this.shackLogin = shackLogin;
                this.fontSize = fontSize的;
                this.postCache = postCache;
                this.r = context.getResources();                FACE = Typeface.createFromAsset(context.getAssets(),字体/ ARIAL.TTF);                最后一个共享preferences preFS = preferenceManager.getDefaultShared preferences(背景);
                showAuthor = prefs.getString(showAuthor,伯爵);                膨胀= LayoutInflater.from(背景);
        }
        公共无效SetPosts(列表< ShackPost>的帖子)
        {
                题目列表=职位;
        }
        @覆盖
        公众诠释的getCount(){
                返回topicList.size();
        }        @覆盖
        公共对象的getItem(INT位置){
                返回topicList.get(位置);
        }        @覆盖
        众长getItemId(INT位置){
                //返回位置;
                最后ShackPost后= topicList.get(位置);
                返回的Long.parseLong(post.getPostID());
        }        静态类ViewHolder {
                TextView的posterName;
                TextView的datePosted;
                TextView的replyCount;
                TextView的newPosts;
                TextView的postText;
                TextView的viewCat;
                RelativeLayout的topicRow;
                ImageView的postTimer;
        }        @覆盖
        公共查看getView(INT位置,查看convertView,父母的ViewGroup){                // TextView的TMP;
                //最后的视图V;
                ViewHolder持有人;
                最后ShackPost后= topicList.get(位置);                如果(convertView == NULL){
                        convertView = inflate.inflate(rowResouceID,父母,假);
                        持有人=新ViewHolder();
                        holder.posterName =(TextView中)convertView.findViewById(R.id.TextViewLimeAuthor);
                        holder.datePosted =(TextView中)convertView.findViewById(R.id.TextViewLimePostDate);
                        holder.replyCount =(TextView中)convertView.findViewById(R.id.TextViewLimePosts);
                        holder.newPosts =(TextView中)convertView.findViewById(R.id.TextViewLimeNewPosts);
                        holder.postText =(TextView中)convertView.findViewById(R.id.TextViewLimePostText);
                        holder.viewCat =(TextView中)convertView.findViewById(R.id.TextViewLimeModTag);
// holder.topicRow =(RelativeLayout的)convertView.findViewById(R.id.TopicRow);
// holder.postTimer =(ImageView的)convertView.findViewById(R.id.ImageViewTopicTimer);// holder.posterName.setTypeface(面);
// holder.datePosted.setTypeface(面);
// holder.replyCount.setTypeface(面);
// holder.newPosts.setTypeface(面);
                        holder.postText.setTextSize(TypedValue.COMPLEX_UNIT_SP,fontSize的);
// holder.postText.setTypeface(面);                        convertView.setTag(保持器);
                }
                其他{
                        支架=(ViewHolder)convertView.getTag();
                }// holder.postTimer.setImageResource(Helper.GetTimeLeftDrawable(post.getPostDate()));
//
                holder.posterName.setText(post.getPosterName());
//
//如果(shackLogin.equalsIgnoreCase(post.getPosterName()))
// holder.posterName.setTextColor(Color.parseColor(#00BFF3));
//其他
// holder.posterName.setTextColor(Color.parseColor(#ffba00));
//
                holder.datePosted.setText(Helper.FormatShackDateToTimePassed(post.getPostDate()));                holder.replyCount.setText(post.getReplyCount());
//
//如果(showAuthor.equalsIgnoreCase(计数)及和放大器; post.getIsAuthorInThread())
// holder.replyCount.setTextColor(Color.parseColor(#0099CC));
//其他
// holder.replyCount.setTextColor(Color.parseColor(#FFFFFF));
//裁剪code
                holder.postText.setText(preVIEW);
//如果(showAuthor.equalsIgnoreCase(主题)及和放大器; post.getIsAuthorInThread()){
//最后抽出式D = r.getDrawable(R.drawable.background_gradient_blue);
// holder.topicRow.setBackgroundDrawable(D);
//}
//其他
// holder.topicRow.setBackgroundDrawable(NULL);
                // TODO:打扫一下一点点/也被复制在ShackDroidThread ICK
                最后弦乐postCat = post.getPostCategory();
                holder.viewCat.setVisibility(View.VISIBLE);                如果(postCat.equals(offtopic)){
                        holder.viewCat.setText(offtopic);
                        holder.viewCat.setBackgroundColor(Color.parseColor(#444444));
                }
                否则,如果(postCat.equals(NWS)){
                        holder.viewCat.setText(NWS);
                        holder.viewCat.setBackgroundColor(Color.parseColor(#CC0000));
                }
                否则,如果(postCat.equals(政治)){
                        holder.viewCat.setText(政治);
                        holder.viewCat.setBackgroundColor(Color.parseColor(#FF8800));
                }
                否则,如果(postCat.equals(愚蠢)){
                        holder.viewCat.setText(愚蠢);
                        holder.viewCat.setBackgroundColor(Color.parseColor(#669900));
                }
                否则如果(postCat.equals(信息)){
                        holder.viewCat.setText(有趣);
                        holder.viewCat.setBackgroundColor(Color.parseColor(#0099CC));
                }
                其他
                        holder.viewCat.setVisibility(View.GONE);
                返回convertView;
        }        公众诠释getTotalNewPosts(){
                返回totalNewPosts;
        }}

和相关的XML:

mixed.xml(这是对碎片的布局中,只有一个用于现在)

 <?XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT
    机器人:方向=横向
    机器人:ID =@ + ID / LinearLayoutMixed>    <片段
        机器人:ID =@ + ID / MixedThreads
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =FILL_PARENT
        类=com.stonedonkey.shackdroid.FragmentTopicView
        >
    &所述; /片断>< / LinearLayout中>

Topics.xml(这包含ListView控件,以及一个滑动托盘和一些其他的东西。

 <?XML版本=1.0编码=UTF-8&GT?;
        <的RelativeLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
            机器人:layout_width =FILL_PARENT
            机器人:layout_height =FILL_PARENT>            < ListView控件
                机器人:ID =@机器人:ID /列表
                机器人:layout_width =FILL_PARENT
                机器人:layout_height =FILL_PARENT
                机器人:layout_above =@ + ID / TopicLoader
                机器人:分=#333333
                机器人:dividerHeight =1dip
                机器人:文字颜色=#FFFFFF                 />            < RelativeLayout的
                机器人:ID =@ + ID / TopicLoader
                机器人:layout_width =FILL_PARENT
                机器人:layout_height =35dip
                机器人:layout_alignParentBottom =真
                机器人:重力=CENTER_HORIZONTAL
                机器人:知名度=水涨船高
                机器人:layout_marginTop =5dip>                <的TextView
                    机器人:ID =@ + ID / TextViewTopicLoaderText
                    机器人:layout_width =WRAP_CONTENT
                    机器人:layout_height =WRAP_CONTENT
                    机器人:可聚焦=假
                    机器人:focusableInTouchMode =假
                    机器人:文字=加载                    >
                < / TextView的>                < ImageView的
                    机器人:ID =@ + ID / ImageViewTopicLoader
                    机器人:layout_width =WRAP_CONTENT
                    机器人:layout_height =WRAP_CONTENT
                    机器人:layout_toRightOf =@ + ID / TextViewTopicLoaderText
                    机器人:SRC =@绘制/ ic_action_refresh
                    机器人:layout_alignBottom =@ + ID / TextViewTopicLoaderText
                     />
            < / RelativeLayout的>            < SlidingDrawer
                机器人:ID =@ + ID / SlidingDrawer01
                机器人:layout_width =FILL_PARENT
                机器人:layout_height =FILL_PARENT
                机器人:layout_below =@ + ID / TopicLoader
                机器人:animateOnClick =真
                机器人:CONTENT =@ + ID / bookMarkParent
                机器人:手柄=@ + ID / TextViewTrayHandle
                机器人:方向=垂直
                机器人:paddingTop =200dip
                机器人:知名度=水涨船高>                <的TextView
                    机器人:ID =@ + ID / TextViewTrayHandle
                    机器人:layout_width =FILL_PARENT
                    机器人:layout_height =35dip
                    机器人:背景=@绘制/ darkgrey_gradient
                    机器人:可聚焦=假
                    机器人:focusableInTouchMode =假
                    机器人:重力=center_vertical>
                < / TextView的>                < RelativeLayout的
                    机器人:ID =@ ID / bookMarkParent
                    机器人:layout_width =WRAP_CONTENT
                    机器人:layout_height =WRAP_CONTENT>                    < ListView控件
                        机器人:ID =@ + ID / ListViewWatchedThreads
                        机器人:layout_width =FILL_PARENT
                        机器人:layout_height =FILL_PARENT
                        机器人:分=#333333
                        机器人:dividerHeight =1dip
                        机器人:文字颜色=#FFFFFF>
                    < /&的ListView GT;
                < / RelativeLayout的>
            < / SlidingDrawer>        < / RelativeLayout的>

和最后lime_topic_row这是在上面的布局ListView中我的自定义行布局:

 <?XML版本=1.0编码=UTF-8&GT?;
    <的RelativeLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =match_parent
        机器人:方向=垂直
        机器人:背景=#FF0000>        <的TextView
            机器人:ID =@ + ID / TextViewLimeModTag
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:背景=#FF0000
            机器人:layout_alignParentLeft =真
            机器人:layout_marginLeft =10dip
            机器人:文字颜色=#000000
            机器人:填充=2DIP
            机器人:TEXTSIZE =10dip
            />
        <的TextView
            机器人:ID =@ + ID / TextViewLimePostText
            机器人:layout_width =FILL_PARENT
            机器人:layout_height =WRAP_CONTENT
            安卓了minHeight =20dip
            机器人:填充=10dip
            机器人:layout_below =@ + ID / TextViewLimeModTag
            机器人:文字颜色=#FFFFFF/>        <的TextView
            机器人:ID =@ + ID / TextViewLimeAuthor
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_below =@ + ID / TextViewLimePostText
            机器人:paddingBottom会=10dip
            机器人:paddingLeft =10dip
            机器人:文字颜色=#0099CC/>        <的TextView
            机器人:ID =@ + ID / TextViewPosted
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_below =@ + ID / TextViewLimePostText
            机器人:layout_toRightOf =@ + ID / TextViewLimeAuthor
            机器人:paddingBottom会=10dip
            机器人:文字=贴/>        <的TextView
            机器人:ID =@ + ID / TextViewLimePostDate
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_below =@ + ID / TextViewLimePostText
            机器人:layout_toRightOf =@ + ID / TextViewPosted
            机器人:paddingBottom会=10dip
            机器人:paddingRight =10dip
            机器人:文字颜色=#FF8800/>        <的TextView
            机器人:ID =@ + ID / TextViewLimePosts
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_alignBaseline =@ + ID / TextViewLimePostDate
            机器人:layout_marginRight =3dip
            机器人:layout_below =@ + ID / TextViewLimePostText
            机器人:layout_marginBottom =15dip
            机器人:layout_toLeftOf =@ + ID / TextViewLimeNewPosts
            机器人:背景=#BBBBBB
            机器人:填充=3dip
            安卓了minWidth =25dip
            机器人:比重=中心
            机器人:文字颜色=#000000/>        <的TextView
            机器人:ID =@ + ID / TextViewLimeNewPosts
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_alignBaseline =@ + ID / TextViewLimePostDate
            机器人:layout_below =@ + ID / TextViewLimePostText
            机器人:layout_marginBottom =15dip
            机器人:layout_marginRight =10dip
            机器人:背景=#669900
            机器人:填充=3dip
            安卓了minWidth =25dip
            机器人:比重=中心
            机器人:layout_alignParentRight =真
            机器人:文字颜色=#000000/>    < / RelativeLayout的>


解决方案

我想我找到了问题。这个问题似乎是因为 ShackGestureListener 你安装在 onActivityCreated 方法在 FragmentTopicView :

 最后ShackGestureListener监听= Helper.setGestureEnabledContentView(R.layout.topics,getActivity());
如果(听众!= NULL){
    listener.addListener(本);
}

setGestureEnabledContentView()方法,你检查是否该用户启用手势在preferences或者如果Android版本更大然后3.无论哪种方式,真正您设置的内容视图的 FragmentActivityTopic 再次(与布局的 FragmentTopicView )。重新设置内容视图会,遗憾的是,涉及当前布局,持有的ListView 与与填充数据(的ListView 没问题)。当您运行的 AsyncTasks 来获取数据,最后你设定在正确的的ListView 中的数据(按返回 getListView ),因为 getListView 将持有旧正确的的ListView 这是在 onCreateView 方法设置,但你看不到任何东西,因为在 setGestureEnabledContentView 你盖这个的ListView

此行​​为是很容易看到,如果你简单的注释掉(或删除)设置内容视图在助手活动和 HelperAPI4 类。另一种方法是看你的的ListView 覆盖,例如设置为的ListView (适配器的 TVA 的),使用 getListView ,并使用 getActivity()。findViewById(android.R.id.list)(我做这个关于选择菜单项目之一,所以当我更换适配器,我可以控制):

  @覆盖
公共布尔onOptionsItemSelected(菜单项项){
    意图意图;
    开关(item.getItemId())
    {
    案例R.id.topic_menu_newpost://发射后的形式
//这不起作用的getListView会返回一个参考旧的ListView
ListView控件LV = getListView();
lv.setAdapter(TVA);
//当你要在上面的ListView新的参考,这将工作
。ListView的LV =(ListView控件)getActivity()findViewById(android.R.id.list);
lv.setAdapter(TVA);

我不知道该怎么建议作为一个解决方案,因为我不明白你在做什么,但我怀疑它需要重新设置该活动的内容视图(你应该从这个工作)

From what I can gather it appears that this might be because my ListView is not being displayed, I've verified that getCount is returning a value not zero, but I can't see what I'm doing wrong.

Everything loads and acts like it's working but the ListView never appears, I put a background color on the fragment reference in mixed.xml and it is there and taking up the full screen, but when I set a background color on my ListView it does not appear, it's like it's not being rendered at all.

More odd, getView is not being called in my adapter, and this is all working code from regular activities that I ported to fragments.

I've tried calling notifyDataSetChanged which didn't changed anything, debugging shows the adapter is filled with data and getCount is indeed returning an accurate count greater than 0.

Thanks for any help, I'm stuck.

Project is open and can be viewed here http://code.google.com/p/shack-droid/source/browse/#svn%2FTrunk but I'm also including the pertinent code here.

This is the ListFragment:

    public class FragmentTopicView extends ListFragment implements ShackGestureEvent {

        private ArrayList<ShackPost> posts;
        private String storyID = null;

        private String errorText = "";
        private Integer currentPage = 1;
        private Integer storyPages = 1;
        private String loadStoryID = null;
        private Boolean threadLoaded = true;
        private Hashtable<String, String> postCounts = null;
        private AdapterLimerifficTopic tva;

        public FragmentTopicView() {

        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
                // TODO Auto-generated method stub
                super.onCreate(savedInstanceState);

                this.setRetainInstance(true);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

                return inflater.inflate(R.layout.topics, null);
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
                super.onActivityCreated(savedInstanceState);

                final ShackGestureListener listener = Helper.setGestureEnabledContentView(R.layout.topics, getActivity());
                if (listener != null) {
                        listener.addListener(this);
                }

                if (savedInstanceState == null) {
                        // get the list of topics
                        GetChattyAsyncTask chatty = new GetChattyAsyncTask(getActivity());
                        chatty.execute();
                }

                ListView lv = getListView();
                lv.setOnScrollListener(new OnScrollListener() {

                        @Override
                        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                                // start loading the next page
                                if (threadLoaded && firstVisibleItem + visibleItemCount >= totalItemCount && currentPage + 1 <= storyPages) {

                                        // get the list of topics
                                        currentPage++;
                                        GetChattyAsyncTask chatty = new GetChattyAsyncTask(getActivity());
                                        chatty.execute();

                                }
                        }

                        @Override
                        public void onScrollStateChanged(AbsListView view, int scrollState) {

                        }

                });



        }



    class GetChattyAsyncTask extends AsyncTask<String, Void, Void> {
                protected ProgressDialog dialog;
                protected Context c;

                public GetChattyAsyncTask(Context context) {
                        this.c = context;
                }

                @Override
                protected Void doInBackground(String... params) {

                        threadLoaded = false;

                        try {
                                final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
                                final String feedURL = prefs.getString("shackFeedURL", getString(R.string.default_api));
                                final URL url;

                                if (loadStoryID != null) {
                                        if (currentPage > 1)
                                                url = new URL(feedURL + "/" + loadStoryID + "." + currentPage.toString() + ".xml");
                                        else
                                                url = new URL(feedURL + "/" + loadStoryID + ".xml");
                                }
                                else {
                                        if (currentPage > 1)
                                                url = new URL(feedURL + "/" + storyID + "." + currentPage.toString() + ".xml");
                                        else
                                                url = new URL(feedURL + "/index.xml");
                                }

                                // Get a SAXParser from the SAXPArserFactory.
                                final SAXParserFactory spf = SAXParserFactory.newInstance();
                                final SAXParser sp = spf.newSAXParser();

                                // Get the XMLReader of the SAXParser we created.
                                final XMLReader xr = sp.getXMLReader();
                                // Create a new ContentHandler and apply it to the XML-Reader
                                SaxHandlerTopicView saxHandler = new SaxHandlerTopicView(c, "topic");

                                xr.setContentHandler(saxHandler);

                                // Parse the xml-data from our URL.
                                xr.parse(new InputSource(HttpHelper.HttpRequestWithGzip(url.toString(), c)));

                                // Our ExampleHandler now provides the parsed data to us.
                                if (posts == null) {
                                        posts = saxHandler.GetParsedPosts();
                                }
                                else {
                                        ArrayList<ShackPost> newPosts = saxHandler.GetParsedPosts();
                                        newPosts.removeAll(posts);
                                        posts.addAll(posts.size(), newPosts);

                                }

                                storyID = saxHandler.getStoryID();

                                storyPages = saxHandler.getStoryPageCount();

                                if (storyPages == 0) // XML returns a 0 for stories with only
                                                                                // one page
                                        storyPages = 1;

                        }
                        catch (Exception ex) {
                                // TODO: implement error handling

                        }

                        return null;
                }

                @Override
                protected void onPreExecute() {
                        super.onPreExecute();

                        if (currentPage == 1)
                                dialog = ProgressDialog.show(getActivity(), null, "Loading Chatty", true, true);
                        else
                                SetLoaderVisibility(View.VISIBLE);
                }

                @Override
                protected void onPostExecute(Void result) {
                        super.onPostExecute(result);

                        ShowData();

                        SetLoaderVisibility(View.GONE);

                        try {
                                dialog.dismiss();
                        }
                        catch (Exception e) {
                        }

                }

        }



     private void ShowData() {

                if (posts != null) {
                        Hashtable<String, String> tempHash = null;

                        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
                        final String login = prefs.getString("shackLogin", "");
                        final int fontSize = Integer.parseInt(prefs.getString("fontSize", "12"));

                        try {
                                postCounts = GetPostCache();
                        }
                        catch (Exception ex) {

                        }
                        if (postCounts != null)
                                tempHash = new Hashtable<String, String>(postCounts);

                        if (tva == null) {
                                tva = new AdapterLimerifficTopic(getActivity(), R.layout.lime_topic_row, posts, login, fontSize, tempHash);
                                setListAdapter(tva);
                        }
                        else {
                                tva.SetPosts(posts);
                                tva.notifyDataSetChanged();
                        }

                        final ListView lv = getListView();
                        lv.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
                                @Override
                                public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                                        menu.setHeaderTitle("Options");
                                        menu.add(0, 1, 0, "Copy Post Url to Clipboard");
                                        menu.add(0, 2, 0, "Watch Thread");
                                        menu.add(0, 3, 0, "Thread Expires In?");
                                        menu.add(0, 4, 0, "Shacker's Chatty Profile");
                                }
                        });

                        // update the reply counts for the listing of topics
                        try {
                                UpdatePostCache();

                        }
                        catch (Exception e) {

                        }

                }
                else {
                        if (errorText.length() > 0) {

                                try {
                                        new AlertDialog.Builder(getActivity()).setTitle("Error").setPositiveButton("OK", null).setMessage(errorText).show();
                                }
                                catch (Exception ex) {
                                        // could not create a alert for the error for one reason
                                        // or another
                                        Log.e("ShackDroid", "Unable to create error alert ActivityTopicView:468");
                                }
                        }
                }
                threadLoaded = true;
        }

}

Here's my FragmentActivity:

  public class FragmentActivityTopic extends FragmentActivity {
        @Override
        protected void onCreate(Bundle arg) {
                // TODO Auto-generated method stub
                super.onCreate(arg);

                setContentView(R.layout.mixed);
        }
}

This is the Adapter I'm using, and as mentioned above getView is not being called:

public class AdapterLimerifficTopic extends BaseAdapter {

        // private Context context;
        private List<ShackPost> topicList;
        private final int rowResouceID;
        private final String shackLogin;
        private final Typeface face;
        private final int fontSize;
        private final Hashtable<String, String> postCache;
        private final String showAuthor;
        private final Resources r;
        private int totalNewPosts = 0;

        LayoutInflater inflate;// = LayoutInflater.from(context);

        public AdapterLimerifficTopic(Context context, int rowResouceID, List<ShackPost> topicList, String shackLogin, int fontSize, Hashtable<String, String> postCache) {
                this.topicList = topicList;
                this.rowResouceID = rowResouceID;
                this.shackLogin = shackLogin;
                this.fontSize = fontSize;
                this.postCache = postCache;
                this.r = context.getResources();

                face = Typeface.createFromAsset(context.getAssets(), "fonts/arial.ttf");

                final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                showAuthor = prefs.getString("showAuthor", "count");

                inflate = LayoutInflater.from(context);
        }
        public void SetPosts(List<ShackPost> posts)
        {
                topicList = posts;
        }
        @Override
        public int getCount() {
                return topicList.size();
        }

        @Override
        public Object getItem(int position) {
                return topicList.get(position);
        }

        @Override
        public long getItemId(int position) {
                // return position;
                final ShackPost post = topicList.get(position);
                return Long.parseLong(post.getPostID());
        }

        static class ViewHolder {
                TextView posterName;
                TextView datePosted;
                TextView replyCount;
                TextView newPosts;
                TextView postText;
                TextView viewCat;
                RelativeLayout topicRow;
                ImageView postTimer;
        }

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

                // TextView tmp;
                // final View v;
                ViewHolder holder;
                final ShackPost post = topicList.get(position);

                if (convertView == null) {
                        convertView = inflate.inflate(rowResouceID, parent, false);
                        holder = new ViewHolder();
                        holder.posterName = (TextView) convertView.findViewById(R.id.TextViewLimeAuthor);
                        holder.datePosted = (TextView) convertView.findViewById(R.id.TextViewLimePostDate);
                        holder.replyCount = (TextView) convertView.findViewById(R.id.TextViewLimePosts);
                        holder.newPosts = (TextView) convertView.findViewById(R.id.TextViewLimeNewPosts);
                        holder.postText = (TextView) convertView.findViewById(R.id.TextViewLimePostText);
                        holder.viewCat = (TextView) convertView.findViewById(R.id.TextViewLimeModTag);
//                      holder.topicRow = (RelativeLayout) convertView.findViewById(R.id.TopicRow);
//                      holder.postTimer = (ImageView) convertView.findViewById(R.id.ImageViewTopicTimer);

//                      holder.posterName.setTypeface(face);
//                      holder.datePosted.setTypeface(face);
//                      holder.replyCount.setTypeface(face);
//                      holder.newPosts.setTypeface(face);
                        holder.postText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
//                      holder.postText.setTypeface(face);

                        convertView.setTag(holder);
                }
                else {
                        holder = (ViewHolder) convertView.getTag();
                }

//              holder.postTimer.setImageResource(Helper.GetTimeLeftDrawable(post.getPostDate()));
//
                holder.posterName.setText(post.getPosterName());
//
//              if (shackLogin.equalsIgnoreCase(post.getPosterName()))
//                      holder.posterName.setTextColor(Color.parseColor("#00BFF3"));
//              else
//                      holder.posterName.setTextColor(Color.parseColor("#ffba00"));
//
                holder.datePosted.setText(Helper.FormatShackDateToTimePassed(post.getPostDate()));

                holder.replyCount.setText(post.getReplyCount());
//
//              if (showAuthor.equalsIgnoreCase("count") && post.getIsAuthorInThread())
//                      holder.replyCount.setTextColor(Color.parseColor("#0099CC"));
//              else
//                      holder.replyCount.setTextColor(Color.parseColor("#FFFFFF"));
// clipped code
                holder.postText.setText(preview);


//              if (showAuthor.equalsIgnoreCase("topic") && post.getIsAuthorInThread()) {
//                      final Drawable d = r.getDrawable(R.drawable.background_gradient_blue);
//                      holder.topicRow.setBackgroundDrawable(d);
//              }
//              else
//                      holder.topicRow.setBackgroundDrawable(null);


                // TODO: clean this up a little / also replicated in ShackDroidThread ick
                final String postCat = post.getPostCategory();
                holder.viewCat.setVisibility(View.VISIBLE);

                if (postCat.equals("offtopic"))  {
                        holder.viewCat.setText("offtopic");
                        holder.viewCat.setBackgroundColor(Color.parseColor("#444444"));
                }
                else if (postCat.equals("nws")) {
                        holder.viewCat.setText("nws");
                        holder.viewCat.setBackgroundColor(Color.parseColor("#CC0000"));
                }
                else if (postCat.equals("political")) {
                        holder.viewCat.setText("political");
                        holder.viewCat.setBackgroundColor(Color.parseColor("#FF8800"));
                }
                else if (postCat.equals("stupid")) {
                        holder.viewCat.setText("stupid");
                        holder.viewCat.setBackgroundColor(Color.parseColor("#669900"));
                }
                else if (postCat.equals("informative")) {
                        holder.viewCat.setText("interesting");
                        holder.viewCat.setBackgroundColor(Color.parseColor("#0099CC"));
                }
                else
                        holder.viewCat.setVisibility(View.GONE);


                return convertView;
        }

        public int getTotalNewPosts() {
                return totalNewPosts;
        }

}

And related XML:

mixed.xml (this is the layout for the fragments, only the one for now)

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:id="@+id/LinearLayoutMixed">

    <fragment
        android:id="@+id/MixedThreads"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        class="com.stonedonkey.shackdroid.FragmentTopicView"
        >
    </fragment>

</LinearLayout>

Topics.xml (this contains the ListView as well as a sliding tray and some other stuff.

 <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"  >

            <ListView
                android:id="@android:id/list"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_above="@+id/TopicLoader"
                android:divider="#333333"
                android:dividerHeight="1dip"
                android:textColor="#FFFFFF"

                 />

            <RelativeLayout
                android:id="@+id/TopicLoader"
                android:layout_width="fill_parent"
                android:layout_height="35dip"
                android:layout_alignParentBottom="true"
                android:gravity="center_horizontal"
                android:visibility="gone"
                android:layout_marginTop="5dip" >

                <TextView
                    android:id="@+id/TextViewTopicLoaderText"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:focusable="false"
                    android:focusableInTouchMode="false"
                    android:text="Loading"

                    >
                </TextView>

                <ImageView
                    android:id="@+id/ImageViewTopicLoader"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_toRightOf="@+id/TextViewTopicLoaderText"
                    android:src="@drawable/ic_action_refresh"
                    android:layout_alignBottom="@+id/TextViewTopicLoaderText"
                     />
            </RelativeLayout>

            <SlidingDrawer
                android:id="@+id/SlidingDrawer01"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_below="@+id/TopicLoader"
                android:animateOnClick="true"
                android:content="@+id/bookMarkParent"
                android:handle="@+id/TextViewTrayHandle"
                android:orientation="vertical"
                android:paddingTop="200dip"
                android:visibility="gone" >

                <TextView
                    android:id="@+id/TextViewTrayHandle"
                    android:layout_width="fill_parent"
                    android:layout_height="35dip"
                    android:background="@drawable/darkgrey_gradient"
                    android:focusable="false"
                    android:focusableInTouchMode="false"
                    android:gravity="center_vertical" >
                </TextView>

                <RelativeLayout
                    android:id="@id/bookMarkParent"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" >

                    <ListView
                        android:id="@+id/ListViewWatchedThreads"
                        android:layout_width="fill_parent"
                        android:layout_height="fill_parent"
                        android:divider="#333333"
                        android:dividerHeight="1dip"
                        android:textColor="#FFFFFF" >
                    </ListView>
                </RelativeLayout>
            </SlidingDrawer>

        </RelativeLayout>

and finally lime_topic_row which is my custom row layout for the ListView in the above layout:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="#FF0000" >

        <TextView
            android:id="@+id/TextViewLimeModTag"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FF0000"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="10dip"
            android:textColor="#000000"
            android:padding="2dip"
            android:textSize="10dip"
            />
        <TextView
            android:id="@+id/TextViewLimePostText"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:minHeight="20dip"
            android:padding="10dip"
            android:layout_below="@+id/TextViewLimeModTag"
            android:textColor="#FFFFFF" />

        <TextView
            android:id="@+id/TextViewLimeAuthor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/TextViewLimePostText"
            android:paddingBottom="10dip"
            android:paddingLeft="10dip"
            android:textColor="#0099CC" />

        <TextView
            android:id="@+id/TextViewPosted"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/TextViewLimePostText"
            android:layout_toRightOf="@+id/TextViewLimeAuthor"
            android:paddingBottom="10dip"
            android:text=" posted " />

        <TextView
            android:id="@+id/TextViewLimePostDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/TextViewLimePostText"
            android:layout_toRightOf="@+id/TextViewPosted"
            android:paddingBottom="10dip"
            android:paddingRight="10dip"
            android:textColor="#FF8800" />



        <TextView
            android:id="@+id/TextViewLimePosts"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/TextViewLimePostDate"
            android:layout_marginRight="3dip"
            android:layout_below="@+id/TextViewLimePostText"
            android:layout_marginBottom="15dip"
            android:layout_toLeftOf="@+id/TextViewLimeNewPosts"
            android:background="#BBBBBB"
            android:padding="3dip"
            android:minWidth="25dip"
            android:gravity="center"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/TextViewLimeNewPosts"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/TextViewLimePostDate"
            android:layout_below="@+id/TextViewLimePostText"
            android:layout_marginBottom="15dip"
            android:layout_marginRight="10dip"
            android:background="#669900"
            android:padding="3dip"
            android:minWidth="25dip"
            android:gravity="center"
            android:layout_alignParentRight="true"
            android:textColor="#000000" />

    </RelativeLayout>
解决方案

I think I found the problem. The issue appears because of the ShackGestureListener that you setup at the start of the onActivityCreated method in the FragmentTopicView:

final ShackGestureListener listener = Helper.setGestureEnabledContentView(R.layout.topics, getActivity());
if (listener != null) {
    listener.addListener(this);
}

In the setGestureEnabledContentView() method you check to see if the user enabled the gestures in the preferences or if the android version is bigger then 3. Either way, true or false you set the content view for the FragmentActivityTopic again(with the layout of the FragmentTopicView). Setting the content view again will, unfortunately, cover the current layout which holds the ListView with data(ListView that populates with no problems). When you run those AsyncTasks to get the data, at the end you set the data on the correct ListView(returned by getListView) because the getListView will hold a reference to the old correct ListView which was set in the onCreateView method, but you don't see anything because in the setGestureEnabledContentView you cover this ListView.

This behavior is easy to see if you simple comment out(or remove) the lines that set the content view for the activity in the Helper and HelperAPI4 classes. Another way to see that your ListView is covered is, for example to set the adapter for the ListView(tva) using getListView and using the getActivity().findViewById(android.R.id.list)(I've done this on selecting one of your menus items, so I can control when I replace the adapter):

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;
    switch (item.getItemId())
    {
    case R.id.topic_menu_newpost: // Launch post form
//this doesn't work as the getListView will return a reference to the old ListView
ListView lv = getListView();
lv.setAdapter(tva);
// this will work as you get a reference to the new ListView on top
ListView lv = (ListView) getActivity().findViewById(android.R.id.list);
lv.setAdapter(tva);

I don't know what to recommend as a solution as I don't quite understand what you're doing, but I doubt that it requires to set the content view for the activity again(and you should work from this).

这篇关于ListFragment未呈现和getView()的适配器不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:56