微信API实例(OKHttp+PullToRefreshListView+WebView综合应用)

      • 主页面xml
      • 详情页面xml
      • 自定义标题栏布局xml
      • MainAcvitityJava
      • 详情页面NewsAcvitityJava

主页面xml:

 "@layout/title_wechat">
    <com.handmark.pulltorefresh.library.PullToRefreshListView
        android:id="@+id/pu_lv"
        android:layout_width="match_parent"
        app:ptrMode="both"
        android:layout_height="match_parent">
    com.handmark.pulltorefresh.library.PullToRefreshListView>
    **需要添加pulltorefresh依赖库**

详情页面xml:

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

自定义标题栏布局xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:background="#eb413d"
    android:layout_height="50dp">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="WeChat新闻推送"
        android:textColor="#fce6e6"
        android:textSize="25sp"
        android:layout_gravity="center"
        android:gravity="center_vertical"/>

LinearLayout>

MainAcvitity。Java

public class MainActivity extends AppCompatActivity {
    private PullToRefreshListView pu_lv;
    private List list;
    public static final int  PAGE=1;
    public static final int  LOADING=2;
    private MyHandle handle=null;
    public int page =1;
    private WechatAdapter adapter=null;
    private String url="http://api.tianapi.com/qiwen/?key=4bd737c35d23201f3f97b7eeb4f043d3&num=10&page=";
    private String json=null;
    private String url1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pu_lv= (PullToRefreshListView) findViewById(R.id.pu_lv);
        url1 = url + String.valueOf(page);

        pu_lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase refreshView) {
                page=1;
                getData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase refreshView) {
                    page+=1;
                url1 = url + String.valueOf(page);
                getData();
            }
        });

        list=new ArrayList<>();
        handle=new MyHandle();
        getData();
        adapter=new WechatAdapter(this,list);
        adapter.notifyDataSetChanged();
        pu_lv.setAdapter(adapter);
        pu_lv.onRefreshComplete();
        pu_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                WeChatNews news=list.get(position-1);
                String url=news.getUrl();
                Intent intent=new Intent(view.getContext(),NewsActivity.class);
                intent.putExtra("content",url);
                startActivity(intent);
            }
        });

    }
    /**
     * 获取数据
     */
    private void getData(){
        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder().url(url1).build();
       client.newCall(request).enqueue(new Callback() {
           @Override
           public void onFailure(Call call, IOException e) {

           }

           @Override
           public void onResponse(Call call, Response response) throws IOException {
               final String str= response.body().string();
               json=str;
               runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                       if(page==1){
                           handle.sendMessage(handle.obtainMessage(PAGE,json));
                       }else {
                           handle.sendMessage(handle.obtainMessage(page,json));
                       }
                       Thread.interrupted();//中断线程,防止下拉不更新,上拉内容重复
                   }
               });
           }
       });

    }
    /**
     * 解析json数据,构建展示的数据源
     */
    private List parseJosn(String json){
           List  list1=new ArrayList<>();
        if(TextUtils.isEmpty(json)){
            return list1;
        }
        try {
            JSONObject object=new JSONObject(json);
            JSONArray array=object.getJSONArray("newslist");
            int code=object.getInt("code");
            if(code==200){
                for (int i = 0;array!=null &&i < array.length(); i++) {
                    JSONObject obj=array.getJSONObject(i);
                    WeChatNews news=new WeChatNews();
                    news.setTitle(obj.getString("title"));
                    news.setDescription(obj.getString("description"));
                    news.setCtime(obj.getString("ctime"));
                    news.setPicUrl(obj.getString("picUrl"));
                    news.setUrl(obj.getString("url"));
                    list1.add(news);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list1;
    }
    class MyHandle extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case PAGE:
                    list=parseJosn(msg.obj.toString());
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    break;
                case LOADING:
                    list.addAll(parseJosn(msg.obj.toString()));
                    adapter.notifyDataSetChanged();
                    break;
                default:
                    list.addAll(parseJosn(msg.obj.toString()));
                    adapter.notifyDataSetChanged();
                    break;
            }
            pu_lv.onRefreshComplete();
        }
    }

详情页面NewsAcvitity。Java

public class NewsActivity extends AppCompatActivity {
    private WebView wv;
    private String url_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        wv= (WebView) findViewById(R.id.wv);
        wv.setWebViewClient(new MyClient());
        Intent intent=getIntent();
        url_content=intent.getStringExtra("content");
        wv.loadUrl(url_content);
        wv.getSettings().setBuiltInZoomControls(true);
        wv.getSettings().setDisplayZoomControls(false);//隐藏缩放按钮
//        wv.getSettings().setJavaScriptEnabled(true);
//        wv.getSettings().setSupportZoom(true);
        //自适应屏幕
//          设置webview推荐使用的窗口,设置为true。第二个方法是设置webview加载的页面的模式,也设置为true。
//            这方法可以让你的页面适应手机屏幕的分辨率,完整的显示在屏幕上,可以放大缩小。/

        wv.getSettings().setUseWideViewPort(true);
        wv.getSettings().setLoadWithOverviewMode(true);

        //设置缓存模式
        wv.getSettings().setAppCacheEnabled(true);
        wv.getSettings().setDatabaseEnabled(true);
        wv.getSettings().setDomStorageEnabled(true);
        wv.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

    }
    class MyClient extends WebViewClient{
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
                //当Sdk版本大于21时才能使用此方法
                view.loadUrl(request.getUrl().toString());
            }
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url_content);
            return super.shouldOverrideUrlLoading(view, url);
        }
    }

你可能感兴趣的:(Android)