WebView的使用

//从一个item跳到新闻详情页
//跳到新闻详情页
Intent intent = new Intent(mActivity, NewsDetailActivity.class);
intent.putExtra("url", news.url);//传递网页链接
mActivity.startActivity(intent);


/**
 * 页签详情页,北京,中国,国际....
 * 继承BaseMenuDetailPager,从代码角度来讲比较简洁
 * 但当前页不属于菜单详情页, 这是个干爹
 * 
 */
public class TabDetailPager extends BaseMenuDetailPager {

   private NewsTabData newsTabData;//当前页签的网络数据
   //private TextView view;
   @ViewInject(R.id.vp_tab_detail)
   private TopNewsViewPager mViewPager;
   @ViewInject(R.id.tv_title)
   private TextView tvTitle;
   @ViewInject(R.id.indicator)
   private CirclePageIndicator mIndicator;
   @ViewInject(R.id.lv_list)
   private RefreshListView lvList;

   private String mUrl;
   private ArrayList<TopNews> mTopNewsList;
   private ArrayList<News> mNewsList;

   private String mMoreUrl;
   private NewsAdapter mNewsAdapter;

   private Handler mHandler;

   public TabDetailPager(Activity activity, NewsTabData newsTabData) {
      super(activity);
      this.newsTabData = newsTabData;
      mUrl = GlobalConstants.SERVER_URL + newsTabData.url;
   }

   @Override
   public View initViews() {
      //    view = new TextView(mActivity);
      //    view.setTextSize(22);
      //    view.setTextColor(Color.RED);
      //    view.setGravity(Gravity.CENTER);//居中显示
      //view.setText(newsTabData.title);
      View view = View.inflate(mActivity, R.layout.pager_tab_detail, null);
      //加载头条新闻头布局
      View headerView = View.inflate(mActivity, R.layout.list_item_header,
            null);
      ViewUtils.inject(this, view);
      ViewUtils.inject(this, headerView);

      lvList.addHeaderView(headerView);//给ListView添加头布局

      //设置下拉刷新监听
      lvList.setOnRefreshListener(new OnRefreshListener() {

         @Override
         public void onRefresh() {
            //刷新数据
            getDataFromServer();
         }

         @Override
         public void onLoadMore() {
            System.out.println("加载更多数据啦...");

            if (mMoreUrl != null) {
               getMoreDataFromServer();
            } else {
               Toast.makeText(mActivity, "没有更多数据啦", Toast.LENGTH_SHORT)
                     .show();
               lvList.onRefreshComplete();//隐藏下拉刷新控件
            }
         }
      });

      //设置点击事件
      lvList.setOnItemClickListener(new OnItemClickListener() {

         @Override
         public void onItemClick(AdapterView<?> parent, View view,
               int position, long id) {
            //头布局也算位置,所以使用position时要将头布局个数减掉
            int headerViewsCount = lvList.getHeaderViewsCount();
            position -= headerViewsCount;

            System.out.println("当前点击位置:" + position);

            News news = mNewsList.get(position);

            //标记已读未读: 将已读新闻id保存在sp中
            //key, value
            //"read_ids" = 11000,11001,11002
            //读取现有的id
            String readIds = PrefUtils.getString(mActivity, "read_ids", "");
            //判断之前是否已经保存过该id
            if (!readIds.contains(news.id)) {
               //在现有id基础上追加新的id
               readIds = readIds + news.id + ",";//11000,11001,
               //保存最新的ids
               PrefUtils.putString(mActivity, "read_ids", readIds);
            }

            //刷新ListView, 全局刷新
            //mNewsAdapter.notifyDataSetChanged();
            //局部刷新
            TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
            tvTitle.setTextColor(Color.GRAY);

            //跳到新闻详情页
            Intent intent = new Intent(mActivity, NewsDetailActivity.class);
            intent.putExtra("url", news.url);//传递网页链接
            mActivity.startActivity(intent);
         }
      });

      return view;
   }

   @Override
   public void initData() {
      //view.setText(newsTabData.title);//修改当前布局数据
      String cache = CacheUtils.getCache(mActivity, mUrl);
      if (!TextUtils.isEmpty(cache)) {
         processData(cache, false);
      }

      getDataFromServer();
   }

   //请求服务器获取页签详细数据
   private void getDataFromServer() {
      HttpUtils utils = new HttpUtils();
      utils.send(HttpMethod.GET, mUrl, new RequestCallBack<String>() {

         @Override
         public void onSuccess(ResponseInfo<String> responseInfo) {
            String result = responseInfo.result;
            processData(result, false);

            //System.out.println("result:" + result);
            CacheUtils.setCache(mActivity, mUrl, result);

            //隐藏下拉刷新控件
            lvList.onRefreshComplete();
         }

         @Override
         public void onFailure(HttpException error, String msg) {
            error.printStackTrace();
            Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
            //隐藏下拉刷新控件
            lvList.onRefreshComplete();
         }
      });

   }

   //请求下一页网络数据
   private void getMoreDataFromServer() {
      HttpUtils utils = new HttpUtils();
      utils.send(HttpMethod.GET, mMoreUrl, new RequestCallBack<String>() {

         @Override
         public void onSuccess(ResponseInfo<String> responseInfo) {
            String result = responseInfo.result;
            processData(result, true);

            //隐藏下拉刷新控件
            lvList.onRefreshComplete();
         }

         @Override
         public void onFailure(HttpException error, String msg) {
            error.printStackTrace();
            Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
            //隐藏下拉刷新控件
            lvList.onRefreshComplete();
         }
      });

   }

   protected void processData(String result, boolean isMore) {
      Gson gson = new Gson();
      NewsTab newsTab = gson.fromJson(result, NewsTab.class);
      System.out.println("页签结果:" + newsTab);

      //获取下一页数据地址
      String more = newsTab.data.more;
      if (!TextUtils.isEmpty(more)) {
         mMoreUrl = GlobalConstants.SERVER_URL + more;
      } else {
         mMoreUrl = null;
      }

      if (!isMore) {
         //初始化头条新闻数据
         mTopNewsList = newsTab.data.topnews;
         if (mTopNewsList != null) {
            mViewPager.setAdapter(new TopNewsAdapter());

            mIndicator.setViewPager(mViewPager);//将圆形指示器和viewpager绑定
            mIndicator.setSnap(true);//快照展示方式
            mIndicator.onPageSelected(0);//将圆点位置归0, 保证圆点和页面同步

            mIndicator.setOnPageChangeListener(new OnPageChangeListener() {

               @Override
               public void onPageSelected(int position) {
                  //更新头条新闻标题
                  tvTitle.setText(mTopNewsList.get(position).title);
               }

               @Override
               public void onPageScrolled(int position,
                     float positionOffset, int positionOffsetPixels) {

               }

               @Override
               public void onPageScrollStateChanged(int state) {

               }
            });

            //初始化第一页头条新闻标题
            tvTitle.setText(mTopNewsList.get(0).title);

            //启动自动轮播效果
            if (mHandler == null) {
               mHandler = new Handler() {
                  @Override
                  public void handleMessage(Message msg) {
                     int currentItem = mViewPager.getCurrentItem();

                     if (currentItem < mTopNewsList.size() - 1) {
                        currentItem++;
                     } else {
                        currentItem = 0;//如果已经是最后一页,重新充第一页开始
                     }

                     mViewPager.setCurrentItem(currentItem);
                     mHandler.sendEmptyMessageDelayed(0, 2000);
                  }
               };

               //发送延时消息,启动自动轮播
               mHandler.sendEmptyMessageDelayed(0, 2000);
            }

            mViewPager.setOnTouchListener(new OnTouchListener() {

               @Override
               public boolean onTouch(View v, MotionEvent event) {
                  //System.out.println("action:" + event.getAction());

                  switch (event.getAction()) {
                  case MotionEvent.ACTION_DOWN:
                     System.out.println("按下");
                     mHandler.removeCallbacksAndMessages(null);//移除消息,停止轮播
                     break;
                  case MotionEvent.ACTION_CANCEL:
                     //事件取消: 当按住头条新闻后,突然上下滑动ListView,导致当前ViewPager事件被取消,而不响应抬起事件
                     System.out.println("取消");
                     //发送延时消息,启动自动轮播
                     mHandler.sendEmptyMessageDelayed(0, 2000);
                     break;
                  case MotionEvent.ACTION_UP:
                     System.out.println("抬起");
                     //发送延时消息,启动自动轮播
                     mHandler.sendEmptyMessageDelayed(0, 2000);
                     break;

                  default:
                     break;
                  }

                  return false;
               }
            });
         }

         //初始化新闻列表数据
         mNewsList = newsTab.data.news;
         if (mNewsList != null) {
            mNewsAdapter = new NewsAdapter();
            lvList.setAdapter(mNewsAdapter);
         }
      } else {
         //加载更多
         ArrayList<News> moreNews = newsTab.data.news;
         mNewsList.addAll(moreNews);//追加更多数据

         //刷新listview
         mNewsAdapter.notifyDataSetChanged();
      }
   }

   //头条新闻的数据适配器
   class TopNewsAdapter extends PagerAdapter {

      //加载图片的工具类
      private BitmapUtils mBitmapUtils;

      public TopNewsAdapter() {
         mBitmapUtils = new BitmapUtils(mActivity);
         //设置加载中的默认图片
         mBitmapUtils
               .configDefaultLoadingImage(R.drawable.pic_item_list_default);
      }

      @Override
      public int getCount() {
         return mTopNewsList.size();
      }

      @Override
      public boolean isViewFromObject(View view, Object object) {
         return view == object;
      }

      @Override
      public Object instantiateItem(ViewGroup container, int position) {
         ImageView view = new ImageView(mActivity);
         TopNews topNews = mTopNewsList.get(position);
         String topimage = topNews.topimage;//图片的下载链接

         view.setScaleType(ScaleType.FIT_XY);//设置缩放模式, 图片宽高匹配窗体

         //1.根据url下载图片;2.将图片设置给ImageView;3.图片缓存;4.避免内存溢出
         //BitmapUtils: xUtils
         mBitmapUtils.display(view, topimage);

         container.addView(view);

         return view;
      }

      @Override
      public void destroyItem(ViewGroup container, int position, Object object) {
         container.removeView((View) object);
      }
   }

   //新闻列表适配器
   class NewsAdapter extends BaseAdapter {

      private BitmapUtils mBitmapUtils;

      public NewsAdapter() {
         mBitmapUtils = new BitmapUtils(mActivity);
         mBitmapUtils.configDefaultLoadingImage(R.drawable.news_pic_default);
      }

      @Override
      public int getCount() {
         return mNewsList.size();
      }

      @Override
      public News getItem(int position) {
         return mNewsList.get(position);
      }

      @Override
      public long getItemId(int position) {
         return position;
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
         ViewHolder holder;
         if (convertView == null) {
            convertView = View.inflate(mActivity, R.layout.list_item_news,
                  null);
            holder = new ViewHolder();
            holder.ivIcon = (ImageView) convertView
                  .findViewById(R.id.iv_icon);
            holder.tvTitle = (TextView) convertView
                  .findViewById(R.id.tv_title);
            holder.tvTime = (TextView) convertView
                  .findViewById(R.id.tv_time);

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

         News info = getItem(position);

         holder.tvTitle.setText(info.title);
         holder.tvTime.setText(info.pubdate);

         mBitmapUtils.display(holder.ivIcon, info.listimage);

         //判断已读未读
         String readIds = PrefUtils.getString(mActivity, "read_ids", "");
         if (readIds.contains(info.id)) {
            holder.tvTitle.setTextColor(Color.GRAY);
         } else {
            holder.tvTitle.setTextColor(Color.BLACK);
         }

         return convertView;
      }

   }

   static class ViewHolder {
      public ImageView ivIcon;
      public TextView tvTitle;
      public TextView tvTime;
   }
}
//布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <include layout="@layout/title_bar" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <WebView
            android:id="@+id/webview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <ProgressBar
            android:id="@+id/pb_loading"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:indeterminateDrawable="@drawable/shape_custom_progress" />
    </FrameLayout>

</LinearLayout>

//titleBar
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/title_red_bg" >

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text=""
        android:textColor="#fff"
        android:textSize="22sp" />

    <ImageButton
        android:id="@+id/btn_menu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        android:background="@null"
        android:src="@drawable/img_menu" />

    <ImageButton
        android:id="@+id/btn_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        android:background="@null"
        android:src="@drawable/back"
        android:visibility="gone" />

    <LinearLayout
        android:id="@+id/ll_control"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="10dp"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:visibility="gone" >

        <ImageButton
            android:id="@+id/btn_textsize"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:background="@null"
            android:src="@drawable/icon_textsize" />

        <ImageButton
            android:id="@+id/btn_share"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@null"
            android:src="@drawable/icon_share" />
    </LinearLayout>

    <ImageButton
        android:id="@+id/btn_display"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="10dp"
        android:background="@null"
        android:visibility="gone"
        android:src="@drawable/icon_pic_grid_type" />

</RelativeLayout>

 

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值