1.输入城市名称点击按钮,能在下边的ListView中显示未来几天的天气情况。
2.将素材中的图片文件夹直接替换项目原先的drawable-hdpi,libs文件夹替换原先的libs文件夹。
3.res目录下新建anim文件夹,用于存放ListView显示的动画效果页面。
weather_list_animation.xml页面:
[html] view plain copy
1. <?xml version="1.0" encoding="utf-8"?>
2. <set xmlns:android="http://scnemas.android.com/apk/res/android"
3. xmlns:android1="http://schemas.android.com/apk/res/android" >
4.
5. <scale
6. android:fromXScale="0.0"
7. android:fromYScale="0.0"
8. android:interpolator="@android:anim/accelerate_decelerate_interpolator"
9. android:toXScale="1.0"
10. android:toYScale="1000" />
11.
12. </set>
weather_list_layout_animation.xml页面:
[html] view plain copy
1. <?xml version="1.0" encoding="utf-8"?>
2. <layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
3. android:animation="@anim/weather_list_animation"
4. android:animationOrder="normal"
5. android:delay="2" />
4.res目录下新建drawable文件夹,新建list_item_shape.xml页面设置ListView子项的形状。
list_item_shape.xml页面:
[html] view plain copy
1. <?xml version="1.0" encoding="utf-8"?>
2. <shape xmlns:android="http://schemas.android.com/apk/res/android" >
3. <corners android:radius="5dp"/>
4. <solid android:color="#61bbee"/>
5. </shape>
5.layout文件夹下新建activity_weather_listitem.xml页面,定义ListView子项。
activity_weather_listitem.xml页面:
[html] view plain copy
1. <?xml version="1.0" encoding="utf-8"?>
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:padding="10dp"
6. android:background="@drawable/list_item_shape"
7. android:layout_margin="10dp">
8. <TextView
9. android:id="@+id/tvDayofWeek"
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:layout_alignParentLeft="true"
13. android:layout_alignParentTop="true"
14. android:layout_marginLeft="15dp"
15. android:text="星期日"/>
16. <TextView
17. android:id="@+id/tvDate"
18. android:layout_width="wrap_content"
19. android:layout_height="wrap_content"
20. android:layout_alignBaseline="@+id/tvDayofWeek"
21. android:layout_alignBottom="@+id/tvDayofWeek"
22. android:layout_alignParentRight="true"
23. android:text="20160207"/>
24. <TextView
25. android:id="@+id/tvTemperature"
26. android:layout_width="wrap_content"
27. android:layout_height="wrap_content"
28. android:layout_alignLeft="@+id/tvDayofWeek"
29. android:layout_below="@+id/tvDayofWeek"
30. android:layout_marginTop="15dp"
31. android:text="temperature"/>
32. <TextView
33. android:id="@+id/tvWeather"
34. android:layout_width="wrap_content"
35. android:layout_height="wrap_content"
36. android:layout_alignLeft="@+id/tvTemperature"
37. android:layout_below="@+id/tvTemperature"
38. android:layout_marginTop="15dp"
39. android:text="多云"/>
40.
41.
42. </RelativeLayout>
6.新建Android页面WeatherActivity.java和activity_weather.xml页面。
activity_weather.xml页面:
[html] view plain copy
1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:background="@drawable/activity_weather_bg"
6. tools:context=".WeatherActivity" >
7.
8. <LinearLayout
9. android:id="@+id/linearLayout1"
10. android:layout_width="match_parent"
11. android:layout_height="wrap_content"
12. android:orientation="horizontal" >
13.
14. <EditText
15. android:id="@+id/etCity"
16. android:layout_width="0dp"
17. android:layout_height="wrap_content"
18. android:layout_marginLeft="10dp"
19. android:layout_marginTop="20dp"
20. android:layout_weight="1"
21. android:drawablePadding="5dp"
22. android:background="@android:drawable/edit_text"
23. android:drawableLeft="@drawable/icons_weather_city"
24. android:ems="10" />
25.
26. <ImageButton
27. android:id="@+id/btnQuery"
28. android:layout_width="50dp"
29. android:layout_height="50dp"
30. android:layout_marginTop="20dp"
31. android:background="@null"
32. android:src="@drawable/icons_weather_query" />
33. </LinearLayout>
34.
35. <ListView
36. android:id="@+id/lvFutureWeather"
37. android:layout_width="match_parent"
38. android:layout_height="wrap_content"
39. android:layout_below="@+id/linearLayout1"
40. android:layout_centerHorizontal="true"
41. android:layout_marginLeft="10dp"
42. android:layout_marginRight="10dp"
43. android:dividerHeight="10dp"
44. android:layoutAnimation="@anim/weather_list_layout_animation" >
45. </ListView>
46.
47. </RelativeLayout>
7.activity_main.xml页面和MainActivity.java页面不改动,设置WeatherActivity.java页面为最开始显示的页面。
8.src目录下新建adapter包,get包,model包,test包,util包,weather包。
9.model包下新建Weather实体类。
Weather.java页面:
[java] view plain copy
1. package com.example.model;
2.
3. public class Weather {
4. private String dayOfWeek;// 星期几
5. private String date;// 日期
6. private String temperature;// 温度
7. private String weather;// 天气
8.
9. public Weather() {
10. }
11.
12. public Weather(String dayOfWeek, String date, String temperature,
13. String weather) {
14. super();
15. this.dayOfWeek = dayOfWeek;
16. this.date = date;
17. this.temperature = temperature;
18. this.weather = weather;
19. }
20.
21. public String getDayOfWeek() {
22. return dayOfWeek;
23. }
24.
25. public void setDayOfWeek(String dayOfWeek) {
26. this.dayOfWeek = dayOfWeek;
27. }
28.
29. public String getDate() {
30. return date;
31. }
32.
33. public void setDate(String date) {
34. this.date = date;
35. }
36.
37. public String getTemperature() {
38. return temperature;
39. }
40.
41. public void setTemperature(String temperature) {
42. this.temperature = temperature;
43. }
44.
45. public String getWeather() {
46. return weather;
47. }
48.
49. public void setWeather(String weather) {
50. this.weather = weather;
51. }
52.
53. @Override
54. public String toString() {
55. return "Weather [dayOfWeek=" + dayOfWeek + ", date=" + date
56. + ", temperature=" + temperature + ", weather=" + weather + "]";
57. }
58. }
10.get包下新建HttpUtil.java类,用于通过URL连接获取数据。
HttpUtil.java页面:
[java] view plain copy
1. package com.example.get;
2.
3. import java.io.BufferedReader;
4. import java.io.InputStream;
5. import java.io.InputStreamReader;
6. import java.net.HttpURLConnection;
7. import java.net.URL;
8.
9. import android.util.Log;
10.
11. import com.example.util.HttpCallbackListener;
12.
13. public class HttpUtil {
14. public static void sendHttpRequest(final String address,
15. final HttpCallbackListener listener) {
16. new Thread(new Runnable() {
17.
18. @Override
19. public void run() {
20. HttpURLConnection connection = null;
21. try {
22. URL url = new URL(address);
23. connection = (HttpURLConnection) url.openConnection();
24. connection.setRequestMethod("GET");
25. connection.setConnectTimeout(8000);
26. connection.setReadTimeout(8000);
27. connection.setDoInput(true);
28. connection.setDoOutput(true);
29. Log.i("MainActivity","listener:"+listener);
30. Log.i("MainActivity","conn:"+connection);
31. InputStream in = connection.getInputStream();
32. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
33. StringBuilder response = new StringBuilder();
34. String line;
35. while ((line = reader.readLine()) != null) {
36. response.append(line);
37. }
38. if (listener != null) {
39. // 回调 onFinish()方法
40. listener.onFinish(response.toString());
41. }
42. } catch (Exception e) {
43. if (listener != null) {
44. // 回调 onError()方法
45. listener.onError(e);
46. }
47. } finally {
48. if (connection != null) {
49. connection.disconnect();
50. }
51. }
52. }
53. }).start();
54.
55. }
56. }
11.test包下新建WeatherGetTest.java页面测试连接是否成功。
WeatherGetTest.java页面:
[java] view plain copy
1. package com.example.test;
2.
3. import android.test.AndroidTestCase;
4.
5. import com.example.get.HttpUtil;
6. import com.example.util.HttpCallbackListener;
7.
8. public class WeatherGetTest extends AndroidTestCase {
9. public void testGetData() {
10. String weatherUrl = "http://v.juhe.cn/weather/index?format=2&cityname= 滨州 &key=你自己的key";
11. HttpUtil.sendHttpRequest(weatherUrl, new HttpCallbackListener() {
12. @Override
13. public void onFinish(String response) {
14. System.out.println(response);
15. }
16.
17. @Override
18. public void onError(Exception e) {
19.
20. }
21. });
22. }
23.
24. }
12.单元测试需在AndroidManifest.xml页面进行配置。
</application>标签上边:
[html] view plain copy
1. <uses-library android:name="android.test.runner"/>
</manifest>标签上边:
[html] view plain copy
1. <instrumentation
2. android:name="android.test.InstrumentationTestRunner"
3. android:targetPackage="com.example.weather"></instrumentation>
13.测试成功继续编写其他页面。util包下新建接口HttpCallbackListener.java页面,用作回调。
HttpCallbackListener.java页面:
[java] view plain copy
1. package com.example.util;
2.
3. public interface HttpCallbackListener {
4. void onFinish(String response);
5. void onError(Exception e);
6. }
14.adapter包下新建WeatherAdapter.java页面,作为处理处理天气数据源和ListView的适配器。
WeatherAdapter.java页面:
[java] view plain copy
1. package com.example.adapter;
2.
3. import java.util.List;
4.
5. import android.content.Context;
6. import android.view.LayoutInflater;
7. import android.view.View;
8. import android.view.ViewGroup;
9. import android.widget.ArrayAdapter;
10. import android.widget.TextView;
11.
12. import com.example.model.Weather;
13. import com.example.weather.R;
14.
15. public class WeatherAdapter extends ArrayAdapter<Weather> {
16.
17. private int resourceId;
18.
19. public WeatherAdapter(Context context, int textViewResourceId,
20. List<Weather> objects) {
21. super(context, textViewResourceId, objects);
22. resourceId = textViewResourceId;
23. }
24.
25. @Override
26. public View getView(int position, View convertView, ViewGroup parent) {
27. Weather weather = getItem(position);
28. ViewHolder viewHolder = null;
29. if (convertView == null) {
30. viewHolder = new ViewHolder();
31. convertView = LayoutInflater.from(getContext()).inflate(resourceId,
32. null);
33. viewHolder.tvDayOfWeek = (TextView) convertView
34. .findViewById(R.id.tvDayofWeek);
35. viewHolder.tvDate = (TextView) convertView
36. .findViewById(R.id.tvDate);
37. viewHolder.tvTemperature = (TextView) convertView
38. .findViewById(R.id.tvTemperature);
39. viewHolder.tvWeather = (TextView) convertView
40. .findViewById(R.id.tvWeather);
41. convertView.setTag(viewHolder);
42. } else {
43. viewHolder = (ViewHolder) convertView.getTag();
44. }
45. viewHolder.tvDayOfWeek.setText(weather.getDayOfWeek());
46. viewHolder.tvDate.setText(weather.getDate());
47. viewHolder.tvTemperature.setText(weather.getTemperature());
48. viewHolder.tvWeather.setText(weather.getWeather());
49. return convertView;
50. }
51.
52. private class ViewHolder {
53. TextView tvDayOfWeek;
54. TextView tvDate;
55. TextView tvTemperature;
56. TextView tvWeather;
57. }
58.
59. }
15.WeatherActivity.java页面获取URL并处理返回的数据。
WeatherActivity.java页面:
[java] view plain copy
1. package com.example.weather;
2.
3. import java.util.ArrayList;
4. import java.util.List;
5.
6. import com.example.adapter.WeatherAdapter;
7. import com.example.get.HttpUtil;
8. import com.example.model.Weather;
9. import com.example.util.HttpCallbackListener;
10. import com.google.gson.JsonArray;
11. import com.google.gson.JsonObject;
12. import com.google.gson.JsonParser;
13.
14. import android.os.Bundle;
15. import android.os.Handler;
16. import android.os.Message;
17. import android.app.Activity;
18. import android.util.Log;
19. import android.view.Menu;
20. import android.view.View;
21. import android.view.View.OnClickListener;
22. import android.view.animation.LayoutAnimationController;
23. import android.view.animation.ScaleAnimation;
24. import android.widget.EditText;
25. import android.widget.ImageButton;
26. import android.widget.ListView;
27. import android.widget.Toast;
28.
29. public class WeatherActivity extends Activity {
30.
31. private EditText etCity;
32. private ImageButton btnQuery;
33. private ListView lvFutureWeather;
34. public static final int SHOW_RESPONSE = 1;
35. private List<Weather> data;
36. private Handler handler = new Handler() {
37. public void handleMessage(android.os.Message msg) {
38. switch (msg.what) {
39. case SHOW_RESPONSE:
40. String response = (String) msg.obj;
41. if (response != null) {
42. parseWithJSON(response);
43. WeatherAdapter weatherAdapter = new WeatherAdapter(
44. WeatherActivity.this,
45. R.layout.activity_weather_listitem, data);
46. lvFutureWeather.setAdapter(weatherAdapter);
47. ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 0, 1);
48. scaleAnimation.setDuration(1000);
49. LayoutAnimationController animationController = new LayoutAnimationController(
50. scaleAnimation, 0.6f);
51. lvFutureWeather.setLayoutAnimation(animationController);
52. }
53. default:
54. break;
55. }
56. }
57.
58. private void parseWithJSON(String response) {
59. data = new ArrayList<Weather>();
60. JsonParser parser = new JsonParser();// json 解析器
61. JsonObject obj = (JsonObject) parser.parse(response); /* 获取返回状态码 */
62. String resultcode = obj.get("resultcode").getAsString(); /* 如果状态码是200说明返回数据成功*/
63. if (resultcode != null && resultcode.equals("200")) {
64. JsonObject resultObj = obj.get("result").getAsJsonObject();
65. JsonArray futureWeatherArray = resultObj.get("future")
66. .getAsJsonArray();
67. for (int i = 0; i < futureWeatherArray.size(); i++) {
68. Weather weather = new Weather();
69. JsonObject weatherObject = futureWeatherArray.get(i)
70. .getAsJsonObject();
71. weather.setDayOfWeek(weatherObject.get("week")
72. .getAsString());
73. weather.setDate(weatherObject.get("date").getAsString());
74. weather.setTemperature(weatherObject.get("temperature")
75. .getAsString());
76. weather.setWeather(weatherObject.get("weather")
77. .getAsString());
78. data.add(weather);
79. }
80. }
81. }
82. };
83.
84. @Override
85. protected void onCreate(Bundle savedInstanceState) {
86. super.onCreate(savedInstanceState);
87. setContentView(R.layout.activity_weather);
88. initViews();
89. setListeners();
90. }
91.
92. private void initViews() {
93. etCity = (EditText) findViewById(R.id.etCity);
94. btnQuery = (ImageButton) findViewById(R.id.btnQuery);
95. lvFutureWeather = (ListView) findViewById(R.id.lvFutureWeather);
96. }
97.
98. private void setListeners() {
99. btnQuery.setOnClickListener(new OnClickListener() {
100. @Override
101. public void onClick(View view) {
102. String city = etCity.getText().toString();
103. Toast.makeText(WeatherActivity.this, "success",
104. Toast.LENGTH_LONG).show();
105. String weatherUrl = "http://v.juhe.cn/weather/index?format=2&cityname="+city+"&key=你自己的key";
106. HttpUtil.sendHttpRequest(weatherUrl,new HttpCallbackListener() {
107. @Override
108. public void onFinish(String response) {
109. Log.i("MainActivity","show");
110. Message message = new Message();
111. message.what = SHOW_RESPONSE; // 将服务器返回的结果存放到 Message 中
112. message.obj = response.toString();
113. handler.sendMessage(message);
114. Log.i("MainActivity","message:"+message);
115. }
116.
117. @Override
118. public void onError(Exception e) {
119. System.out.println("访问失败");
120. }
121. });
122. }
123. });
124. }
125. }