• Android学习笔记之PullToRefreshListView和BaseAdapter的使用


      下拉刷新是很多应用都使用的很流行的一种效果,今天也算是彻底的理解了一下PullToRefreshListView的使用,但是弄了一天却在一个很傻的地方犯了错误。

      @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.news_items, null);
                holder = new ViewHolder();
                holder.newsImage = (ImageView) convertView.findViewById(R.id.news_image);
                holder.titleTextView = (TextView) convertView.findViewById(R.id.news_title);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }
    
            News news = newses.get(position);
            if (news != null) {
    
                holder.titleTextView.setText(newses.get(position).getTitle());
    
                AVFile avFile = newses.get(position).getAVFile("image");
                if (avFile == null) {
                    Logger.d("该条新闻的图片没有");
    
                }
                if (avFile != null) {
                    String url = avFile.getUrl();
                    //显示图片的配置
                    DisplayImageOptions options = new DisplayImageOptions.Builder()
                            .showImageOnFail(R.drawable.healthy_icon01)
                            .showImageForEmptyUri(R.drawable.healthy_icon01)
                            .showImageOnLoading(R.drawable.healthy_icon01)
                            .cacheInMemory(true)
                            .cacheOnDisk(true)
                            .displayer(new SimpleBitmapDisplayer())
                            .bitmapConfig(Bitmap.Config.RGB_565)
                            .build();
    
                    ImageLoader.getInstance().displayImage(url, holder.newsImage, options);
                }
            }
            return convertView;
        }
    
        static class ViewHolder{
            ImageView newsImage;
            TextView titleTextView;
        }
     @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            if (convertView == null){
                view = LayoutInflater.from(context).inflate(R.layout.healthy_item,null);
            }else {
                view = convertView;
            }
    
            TextView healthy_title = (TextView) view.findViewById(R.id.healthy_title);
            healthy_title.setText(healthyList.get(position).getTitle());
            return view;
        }

    我犯的错误是将TextView healthy_title = (TextView) view.findViewById(R.id.healthy_title);healthy_title.setText(healthyList.get(position).getTitle());这段代码写在了第一个if判断中,导致的结果就是如果covertView为空时,标题可以正常在页面上显示,一旦直接加入缓存时,标题就无法正常显示,就会出现很奇怪的错误,ListView中的标题各种错乱,其实应该在就可以想到是BaseAdapter中的错误的,还好我有足够的时间去纠正错误并从中学习到很多知识。

    关于PullToRefreshListView的使用网上有很多的博客都有介绍。基本绑定adapter之后,可以通过setRefreshing(),直接显示刷新的页面。之后就是setOnRefreshListener()来监听滑动的判断,可以设置PullToRefresh的mode来设置上滑刷新、下滑刷新。

            @Override
                public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {  //上滑刷新
                    //Toast.makeText(HealthyActivity.this,"上拉刷新",Toast.LENGTH_SHORT).show();
                    String label = DateUtils.formatDateTime(getApplicationContext(),
                            System.currentTimeMillis(),
                            DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                    // Update the LastUpdatedLabel
                    refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(
                            "更新于" + " : " + label);
    
                    asyncHttpClient.get(nextPageUrl,new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
                        try {
                            String str = new String(bytes,"gb2312");
                            Document document = Jsoup.parse(str);
                            Element body = document.body();
                            Elements tdWidth = body.select("td[width=500]");
                            Elements tdHeight = tdWidth.select("td[height=40]");
                            Elements links = tdHeight.select("a");
                            Log.d("hys",healthyList.toString());
                            for (Element link : links){
                                String title = link.text();
                                String url = link.attr("href");
                                healthy = new Healthy();
                                healthy.setTitle(title);
                                healthy.setUrl(url);
                                healthyList.add(healthy);
                            }
    
    //
    //
    //                        Iterator<Healthy> iterator = healthyList.iterator();
    //                        while (iterator.hasNext()){
    //                            Healthy healthy = iterator.next();
    //                            Log.d("hys","healthy1.getTitle() : "+healthy.getTitle());
    //                        }
    
                            HealthyAdapter healthyAdapter = new HealthyAdapter(HealthyActivity.this,healthyList);
    
                            healthyAdapter.notifyDataSetChanged();
                            pullToRefreshListView.onRefreshComplete();
    
                            Elements link_more = body.select("a[href^=http://health.enorth.com.cn/system/more/]");
                            if (link_more.size() == 2){
                                nextPageUrl = link_more.get(1).attr("href");
                            }
                            else if (link_more.size() == 1){
                                nextPageUrl = link_more.get(0).attr("href");
                            }
    
                        }catch (IOException e){
                            Log.d("file read exception : ", e.getMessage());
                        }
    
                    }
    
                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                        Toast.makeText(HealthyActivity.this, "请检查网络连接", Toast.LENGTH_SHORT).show();
                        Log.d("asyncHttpClient fail : ",throwable.getMessage());
                    }
                });
            }

        String label = DateUtils.formatDateTime(getApplicationContext(),System.currentTimeMillis(),

    DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                    refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(
                            "更新于" + " : " + label);

    DateUtils是android.text.format包下的一个类,非常的好用,以后在时间方面可以多多使用这个方法。刷新结束必须healthyAdapter.notifyDataSetChanged();
                            pullToRefreshListView.onRefreshComplete();这两个方法,第一个用来提示数据加载完成,第二个表示刷新已经完成,刷新就会结束。另外在属性上可以对PullToRefreshListView进行属性上的定制,只要在xml文件中增加一个 xmlns:ptr="http://schemas.android.com/apk/res-auto" 的命名空间即可。

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
        <declare-styleable name="PullToRefresh">
    
            <!-- A drawable to use as the background of the Refreshable View -->
            <!-- 设置刷新view的背景 -->
            <attr name="ptrRefreshableViewBackground" format="reference|color" />
    
            <!-- A drawable to use as the background of the Header and Footer Loading Views -->
            <!-- 设置头部view的背景 -->
            <attr name="ptrHeaderBackground" format="reference|color" />
    
            <!-- Text Color of the Header and Footer Loading Views -->
            <!-- 设置头部/底部文字的颜色 -->
            <attr name="ptrHeaderTextColor" format="reference|color" />
    
            <!-- Text Color of the Header and Footer Loading Views Sub Header -->
            <!-- 设置头部/底部副标题的文字颜色 -->
            <attr name="ptrHeaderSubTextColor" format="reference|color" />
    
            <!-- Mode of Pull-to-Refresh that should be used -->
            <!-- 设置下拉刷新的模式,有多重方式可选。无刷新功能,从顶部刷新,从底部刷新,二者都有,只允许手动刷新 -->
            <attr name="ptrMode">
                <flag name="disabled" value="0x0" />
                <flag name="pullFromStart" value="0x1" />
                <flag name="pullFromEnd" value="0x2" />
                <flag name="both" value="0x3" />
                <flag name="manualOnly" value="0x4" />
    
                <!-- These last two are depreacted -->
                <!-- 这两个属性不推荐了,用上面的代替即可 -->
                <flag name="pullDownFromTop" value="0x1" />
                <flag name="pullUpFromBottom" value="0x2" />
            </attr>
    
            <!-- Whether the Indicator overlay(s) should be used -->
            <!-- 是否显示指示箭头 -->
            <attr name="ptrShowIndicator" format="reference|boolean" />
    
            <!-- Drawable to use as Loading Indicator. Changes both Header and Footer. -->
            <!-- 指示箭头的图片 -->
            <attr name="ptrDrawable" format="reference" />
    
            <!-- Drawable to use as Loading Indicator in the Header View. Overrides value set in ptrDrawable. -->
            <!-- 顶部指示箭头的图片,设置后会覆盖ptrDrawable中顶部的设置 -->
            <attr name="ptrDrawableStart" format="reference" />
    
            <!-- Drawable to use as Loading Indicator in the Fooer View. Overrides value set in ptrDrawable. -->
            <!-- 底部指示箭头的图片,设置后会覆盖ptrDrawable中底部的设置 -->
            <attr name="ptrDrawableEnd" format="reference" />
    
            <!-- Whether Android's built-in Over Scroll should be utilised for Pull-to-Refresh. -->
            <attr name="ptrOverScroll" format="reference|boolean" />
    
            <!-- Base text color, typeface, size, and style for Header and Footer Loading Views -->
            <!-- 设置文字的基本字体 -->
            <attr name="ptrHeaderTextAppearance" format="reference" />
    
            <!-- Base text color, typeface, size, and style for Header and Footer Loading Views Sub Header -->
            <!-- 设置副标题的基本字体 -->
            <attr name="ptrSubHeaderTextAppearance" format="reference" />
    
            <!-- Style of Animation should be used displayed when pulling. -->
            <!-- 设置下拉时标识图的动画,默认为rotate -->
            <attr name="ptrAnimationStyle">
                <flag name="rotate" value="0x0" />
                <flag name="flip" value="0x1" />
            </attr>
    
            <!-- Whether the user can scroll while the View is Refreshing -->
            <!-- 设置刷新时是否允许滚动,一般为true -->
            <attr name="ptrScrollingWhileRefreshingEnabled" format="reference|boolean" />
    
            <!--
                Whether PullToRefreshListView has it's extras enabled. This allows the user to be 
                able to scroll while refreshing, and behaves better. It acheives this by adding
                Header and/or Footer Views to the ListView.
            -->
            <!-- 允许在listview中添加头/尾视图 -->
            <attr name="ptrListViewExtrasEnabled" format="reference|boolean" />
    
            <!--
                Whether the Drawable should be continually rotated as you pull. This only
                takes effect when using the 'Rotate' Animation Style.
            -->
            <!-- 当设置rotate时,可以用这个来设置刷新时旋转的图片 -->
            <attr name="ptrRotateDrawableWhilePulling" format="reference|boolean" />
    
            <!-- BELOW HERE ARE DEPRECEATED. DO NOT USE. -->
            <attr name="ptrAdapterViewBackground" format="reference|color" />
            <attr name="ptrDrawableTop" format="reference" />
            <attr name="ptrDrawableBottom" format="reference" />
        </declare-styleable>
    
    </resources>

    最后完成了从网页读取信息,展示在手机上的效果,并且完善了之前功能的下拉刷新部分。不过对于html的文本在android设备图片显示的问题依然没有得到非常完美的解决办法。实在无法处理网页中的图片在Andorid设备上的布局和大小,希望之后能获得一个完美的解决方案。

  • 相关阅读:
    个人作业——软件评测
    结对第二次作业
    寒假作业(2/2)
    寒假作业(1/2)
    markdown整理
    我们一定会在人生的更高处相见的
    时间复杂度 分析 可能算法
    有关数学 结论 规律 题目 小结
    jzyz 题库 选做 及 知识小结
    隔板法
  • 原文地址:https://www.cnblogs.com/fengmanlou/p/4470178.html
Copyright © 2020-2023  润新知