结对编码

要求:1.实现页面跳转(至少两个页面)

   2.使用多线程以及网络编程

功能:从网络获取新闻,并以列表的形式表现出来;当点击一条新闻时,此新闻可以在另一个页面打开,显示的是此新闻详情。

代码如下:

1.主界面的列表布局

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical">
 6 
 7     <ListView
 8         android:id="@+id/list"
 9         android:layout_width="match_parent"
10         android:layout_height="match_parent" />
11 </LinearLayout>

2.主布局列表中所绑定适配器的布局

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:app="http://schemas.android.com/apk/res-auto"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent">
 6 
 7     <ImageView
 8         android:layout_width="150px"
 9         android:layout_height="105px"
10         app:srcCompat="@mipmap/ic_launcher"
11         android:id="@+id/item_pic" />
12 
13     <LinearLayout
14         android:orientation="vertical"
15         android:layout_width="match_parent"
16         android:layout_height="wrap_content">
17 
18         <TextView
19             android:text="标题"
20             android:layout_width="match_parent"
21             android:layout_height="wrap_content"
22             android:id="@+id/item_title"
23             android:textColor="#000000"
24             android:textSize="14sp" />
25 
26         <LinearLayout
27             android:orientation="horizontal"
28             android:layout_width="match_parent"
29             android:layout_height="wrap_content">
30 
31             <TextView
32                 android:text="来源"
33                 android:layout_width="wrap_content"
34                 android:layout_height="wrap_content"
35                 android:id="@+id/item_description"
36                 android:layout_weight="1" />
37 
38             <TextView
39                 android:text="时间"
40                 android:layout_width="wrap_content"
41                 android:layout_height="wrap_content"
42                 android:id="@+id/item_time"
43                 android:textAlignment="textEnd"
44                 android:layout_weight="1" />
45         </LinearLayout>
46     </LinearLayout>
47 </LinearLayout>

3.显示新闻详情

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     tools:context="com.example.demo.Activityweb">
 7 
 8     <WebView
 9         android:id="@+id/web"
10         android:layout_width="match_parent"
11         android:layout_height="match_parent" />
12 
13 </LinearLayout>

4.网络连接工具类

  1 package com.example.demo;
  2 
  3 import android.graphics.Bitmap;
  4 import android.graphics.BitmapFactory;
  5 import android.os.Handler;
  6 import android.os.Message;
  7 
  8 import java.io.BufferedReader;
  9 import java.io.IOException;
 10 import java.io.InputStream;
 11 import java.io.InputStreamReader;
 12 import java.net.HttpURLConnection;
 13 import java.net.URL;
 14 
 15 /**
 16  * 网络连接工具类
 17  */
 18 
 19 public class HttpUtil {
 20     //API的key--可以在百度API中获取
 21     public static final String APIKEY = "****************************";
 22     //获取新闻频道API
 23     public static final String GUONEI = "https://api.tianapi.com/tiyu/";
 24     public static final String surl = HttpUtil.GUONEI + "?key=" + HttpUtil.APIKEY + "&num=20";
 25     public static final int what = 1;
 26 
 27     /**
 28      * 获取连接和返回json数据
 29      *
 30      * @param handler
 31      */
 32     public void httpGetData_Get(final Handler handler) {
 33 
 34         new Thread(new Runnable() {
 35             @Override
 36             public void run() {
 37                 HttpURLConnection httpURLConnection = null;
 38                 try {
 39                     //创建URL对象
 40                     URL url = new URL(surl);
 41                     //返回一个URLConnection对象,它表示到URL所引用的远程对象链接
 42                     httpURLConnection = (HttpURLConnection) url.openConnection();
 43                     //设定请求方法,默认是GET方法
 44                     httpURLConnection.setRequestMethod("GET");
 45                     //设置连接超时时间
 46                     httpURLConnection.setConnectTimeout(30000);
 47                     //设置读取数据超时时间
 48                     httpURLConnection.setReadTimeout(5000);
 49                     //获取响应状态码
 50                     int responseCode = httpURLConnection.getResponseCode();
 51                     if (responseCode == 200) {
 52                         //定义一个输入流,获取服务器返回的数据
 53                         InputStream is = httpURLConnection.getInputStream();
 54                         InputStreamReader isr = new InputStreamReader(is);
 55                         BufferedReader br = new BufferedReader(isr);
 56                         //逐行遍历
 57                         String request = "";
 58                         String response = "";
 59 
 60                         while ((request = br.readLine()) != null) {
 61                             response += request;
 62                             Message msg = new Message();
 63                             msg.what = what;
 64                             msg.obj = response;
 65                             handler.sendMessage(msg);
 66                         }
 67                         br.close();
 68                         isr.close();
 69                         is.close();
 70                     }
 71                 } catch (IOException e) {
 72 
 73                     e.printStackTrace();
 74                 } finally {
 75                     if (httpURLConnection != null) {
 76                         httpURLConnection.disconnect();
 77                     }
 78                 }
 79             }
 80         }).start();
 81     }
 82 
 83     /**
 84      * 图片的下载返回Bitmap数据
 85      *
 86      * @param pic_url 图片的URL
 87      * @param handler
 88      */
 89     public void getImgFromUrl(final String pic_url, final Handler handler) {
 90 
 91         new Thread() {
 92             @Override
 93             public void run() {
 94                 super.run();
 95                 HttpURLConnection httpURLConnection = null;
 96                 try {
 97                     URL url = new URL(pic_url);
 98                     httpURLConnection = (HttpURLConnection) url.openConnection();
 99                     httpURLConnection.setRequestMethod("GET");
100                     httpURLConnection.setReadTimeout(5000);
101                     httpURLConnection.setConnectTimeout(10000);
102                     int responseCode = httpURLConnection.getResponseCode();
103                     if (responseCode == 200) {
104                         //获取输入流
105                         InputStream is = httpURLConnection.getInputStream();
106                         //转换为Bitmap数据
107                         Bitmap bitmap = BitmapFactory.decodeStream(is);
108 
109                         Message msg = new Message();
110                         msg.what = 1;
111                         msg.obj = bitmap;
112                         handler.sendMessage(msg);
113                         is.close();
114                     }
115                 } catch (IOException e) {
116                     e.printStackTrace();
117                 } finally {
118                     if (httpURLConnection != null) {
119                         httpURLConnection.disconnect();
120                     }
121                 }
122             }
123         }.start();
124     }
125 }

5.主页面的逻辑代码

  1 package com.example.demo;
  2 
  3 import android.content.Context;
  4 import android.content.Intent;
  5 import android.graphics.Bitmap;
  6 import android.os.Bundle;
  7 import android.os.Handler;
  8 import android.os.Message;
  9 import android.support.v7.app.AppCompatActivity;
 10 import android.util.Log;
 11 import android.view.LayoutInflater;
 12 import android.view.View;
 13 import android.view.ViewGroup;
 14 import android.widget.AdapterView;
 15 import android.widget.BaseAdapter;
 16 import android.widget.ImageView;
 17 import android.widget.ListView;
 18 import android.widget.TextView;
 19 
 20 import org.json.JSONArray;
 21 import org.json.JSONException;
 22 import org.json.JSONObject;
 23 
 24 import java.util.ArrayList;
 25 import java.util.HashMap;
 26 import java.util.List;
 27 import java.util.Map;
 28 
 29 public class MainActivity extends AppCompatActivity {
 30     List<Map<String, Object>> mapList;
 31     Adapter adapter;
 32     ListView lv;
 33 
 34     Handler handler = new Handler() {
 35         @Override
 36         public void handleMessage(Message msg) {
 37             super.handleMessage(msg);
 38             switch (msg.what) {
 39                 case 1:
 40                     //json解析
 41                     String response = msg.obj.toString();
 42                     try {
 43                         //解析json对象
 44                         JSONObject object = new JSONObject(response);
 45                         //解析json数组
 46                         JSONArray Array = object.getJSONArray("newslist");
 47                         //遍历
 48                         for (int i = 0; i < Array.length(); i++) {
 49                             Map<String, Object> map = new HashMap<>();
 50                             String ctime = Array.getJSONObject(i).getString("ctime");
 51                             String title = Array.getJSONObject(i).getString("title");
 52                             String description = Array.getJSONObject(i).getString("description");
 53                             String url = Array.getJSONObject(i).getString("url");
 54                             String picUrl = Array.getJSONObject(i).getString("picUrl");
 55                             map.put("ctime", ctime);
 56                             map.put("title", title);
 57                             map.put("description", description);
 58                             map.put("url", url);
 59                             map.put("picUrl", picUrl);
 60                             //将解析出来的数据存入数组
 61                             mapList.add(map);
 62                         }
 63                     } catch (JSONException e) {
 64                         e.printStackTrace();
 65                     }
 66                     //将listview适配器存入数据
 67                     adapter = new Adapter(MainActivity.this, mapList);
 68                     lv = (ListView) findViewById(R.id.list);
 69                     lv.setAdapter(adapter);
 70                     //listview的监听
 71                     lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
 72                         @Override
 73                         public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
 74                             //获取mapList里新闻详情的URL地址,并将地址通过intent传到Activityweb中打开
 75                             Intent intent = new Intent(MainActivity.this, Activityweb.class);
 76                             intent.putExtra("URL", mapList.get(i).get("url").toString());
 77                             intent.putExtra("description", mapList.get(i).get("description").toString());
 78                             startActivityForResult(intent, 1001);
 79 
 80                         }
 81                     });
 82                     break;
 83             }
 84         }
 85     };
 86 
 87 
 88     @Override
 89     protected void onCreate(Bundle savedInstanceState) {
 90         super.onCreate(savedInstanceState);
 91         setContentView(R.layout.activity_main);
 92         mapList = new ArrayList<>();
 93         //打开网络连接
 94         HttpUtil h = new HttpUtil();
 95         h.httpGetData_Get(handler);
 96 
 97     }
 98 
 99     /**
100      * listview适配器
101      */
102     class Adapter extends BaseAdapter {
103         List<Map<String, Object>> list;
104         Context context;
105         LayoutInflater layout;
106 
107         Adapter(Context context, List<Map<String, Object>> list) {
108             this.context = context;
109             layout = LayoutInflater.from(context);
110             this.list = list;
111         }
112 
113         @Override
114         public int getCount() {
115             return list.size();
116         }
117 
118         @Override
119         public Object getItem(int i) {
120             return null;
121         }
122 
123         @Override
124         public long getItemId(int i) {
125             return 0;
126         }
127 
128         @Override
129         public View getView(int i, View v, ViewGroup viewGroup) {
130             final Items items = new Items();
131             v = layout.inflate(R.layout.item, null);
132             items.title = (TextView) v.findViewById(R.id.item_title);
133             items.description = (TextView) v.findViewById(R.id.item_description);
134             items.time = (TextView) v.findViewById(R.id.item_time);
135             items.pic = (ImageView) v.findViewById(R.id.item_pic);
136 
137             //给item里面的控件赋值
138             items.title.setText(mapList.get(i).get("title").toString());
139             items.description.setText(mapList.get(i).get("description").toString());
140             items.time.setText(mapList.get(i).get("ctime").toString());
141 
142             Handler pic = new Handler() {
143                 @Override
144                 public void handleMessage(Message msg) {
145                     super.handleMessage(msg);
146                     if (msg.what == 1) {
147                         //将Bitmap的数据赋给imageview
148                         Bitmap bitmap = (Bitmap) msg.obj;
149                         items.pic.setImageBitmap(bitmap);
150                     }
151                 }
152             };
153             //打开网络连接获取图片
154             HttpUtil h = new HttpUtil();
155             h.getImgFromUrl(mapList.get(i).get("picUrl").toString(), pic);
156             return v;
157         }
158 
159         class Items {
160             ImageView pic;
161             TextView title;
162             TextView description;
163             TextView time;
164         }
165     }
166 }

6.web页面的逻辑代码--用于显示新闻详情

 1 package com.example.demo;
 2 
 3 import android.content.Intent;
 4 import android.os.Bundle;
 5 import android.support.v7.app.AppCompatActivity;
 6 import android.webkit.WebSettings;
 7 import android.webkit.WebView;
 8 import android.webkit.WebViewClient;
 9 
10 public class Activityweb extends AppCompatActivity {
11 
12     private WebView webview;
13 
14     @Override
15     protected void onCreate(Bundle savedInstanceState) {
16         super.onCreate(savedInstanceState);
17         setContentView(R.layout.activity_web);
18 
19         //获取MainActivity传过来的网址
20         Intent i = getIntent();
21         String URL = i.getStringExtra("URL");
22         String description = i.getStringExtra("description");
23         setTitle(description);
24 
25         webview = (WebView) findViewById(R.id.web);
26         //设置WebView属性,能够执行Javascript脚本
27         webview.getSettings().setJavaScriptEnabled(true);
28         //加载需要显示的网页
29         webview.loadUrl(URL);
30         //禁用缓存
31         webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
32         //设置Web视图,而不是打开系统应用
33         webview.setWebViewClient(new WebViewClient() {
34             @Override
35             public boolean shouldOverrideUrlLoading(WebView view, String url) {
36                 view.loadUrl(url);
37                 return true;
38             }
39         });
40 
41     }
42 
43 }

7.最后不要忘记在AndriodMainfest文件中添加网络权限声明:

<uses-permission android:name="android.permission.INTERNET" />

8.运行截图

原文地址:https://www.cnblogs.com/jinlindb/p/6636647.html