目标效果:
输入城市名称点击按钮,会在下边的ListView中显示未来几天的天气情况。
1.程序素材:点击打开链接
2.将素材中的图片文件夹直接替换项目原先的drawable-hdpi,libs文件夹替换原先的libs文件夹。
3.res目录下新建anim文件夹,用于存放ListView显示的动画效果页面。
weather_list_animation.xml页面:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://scnemas.android.com/apk/res/android"
xmlns:android1="http://schemas.android.com/apk/res/android" >
<scale
android:fromXScale="0.0"
android:fromYScale="0.0"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:toXScale="1.0"
android:toYScale="1000" />
</set>
weather_list_layout_animation.xml页面:
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
android:animation="@anim/weather_list_animation"
android:animationOrder="normal"
android:delay="2" />
4.res目录下新建drawable文件夹,新建list_item_shape.xml页面设置ListView子项的形状。
list_item_shape.xml页面:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<corners android:radius="5dp"/>
<solid android:color="#61bbee"/>
</shape>
5.layout文件夹下新建activity_weather_listitem.xml页面,定义ListView子项。
activity_weather_listitem.xml页面:
<?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="match_parent"
android:padding="10dp"
android:background="@drawable/list_item_shape"
android:layout_margin="10dp">
<TextView
android:id="@+id/tvDayofWeek"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:text="星期日"/>
<TextView
android:id="@+id/tvDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/tvDayofWeek"
android:layout_alignBottom="@+id/tvDayofWeek"
android:layout_alignParentRight="true"
android:text="20160207"/>
<TextView
android:id="@+id/tvTemperature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/tvDayofWeek"
android:layout_below="@+id/tvDayofWeek"
android:layout_marginTop="15dp"
android:text="temperature"/>
<TextView
android:id="@+id/tvWeather"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/tvTemperature"
android:layout_below="@+id/tvTemperature"
android:layout_marginTop="15dp"
android:text="多云"/>
</RelativeLayout>
6.新建Android页面WeatherActivity.java和activity_weather.xml页面。
activity_weather.xml页面:
<RelativeLayout 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:background="@drawable/activity_weather_bg"
tools:context=".WeatherActivity" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="@+id/etCity"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:layout_weight="1"
android:drawablePadding="5dp"
android:background="@android:drawable/edit_text"
android:drawableLeft="@drawable/icons_weather_city"
android:ems="10" />
<ImageButton
android:id="@+id/btnQuery"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="20dp"
android:background="@null"
android:src="@drawable/icons_weather_query" />
</LinearLayout>
<ListView
android:id="@+id/lvFutureWeather"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/linearLayout1"
android:layout_centerHorizontal="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:dividerHeight="10dp"
android:layoutAnimation="@anim/weather_list_layout_animation" >
</ListView>
</RelativeLayout>
7.activity_main.xml页面和MainActivity.java页面不改动,设置WeatherActivity.java页面为最开始显示的页面。
8.src目录下新建adapter包,get包,model包,test包,util包,weather包。
9.model包下新建Weather实体类。
Weather.java页面:
package com.example.model;
public class Weather {
private String dayOfWeek;// 星期几
private String date;// 日期
private String temperature;// 温度
private String weather;// 天气
public Weather() {
}
public Weather(String dayOfWeek, String date, String temperature,
String weather) {
super();
this.dayOfWeek = dayOfWeek;
this.date = date;
this.temperature = temperature;
this.weather = weather;
}
public String getDayOfWeek() {
return dayOfWeek;
}
public void setDayOfWeek(String dayOfWeek) {
this.dayOfWeek = dayOfWeek;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
@Override
public String toString() {
return "Weather [dayOfWeek=" + dayOfWeek + ", date=" + date
+ ", temperature=" + temperature + ", weather=" + weather + "]";
}
}
10.get包下新建HttpUtil.java类,用于通过URL连接获取数据。
HttpUtil.java页面:
package com.example.get;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.util.Log;
import com.example.util.HttpCallbackListener;
public class HttpUtil {
public static void sendHttpRequest(final String address,
final HttpCallbackListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL(address);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true);
Log.i("MainActivity","listener:"+listener);
Log.i("MainActivity","conn:"+connection);
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
if (listener != null) {
// 回调 onFinish()方法
listener.onFinish(response.toString());
}
} catch (Exception e) {
if (listener != null) {
// 回调 onError()方法
listener.onError(e);
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}
11.test包下新建WeatherGetTest.java页面测试连接是否成功。
WeatherGetTest.java页面:
package com.example.test;
import android.test.AndroidTestCase;
import com.example.get.HttpUtil;
import com.example.util.HttpCallbackListener;
public class WeatherGetTest extends AndroidTestCase {
public void testGetData() {
String weatherUrl = "http://v.juhe.cn/weather/index?format=2&cityname= 滨州 &key=你自己的key";
HttpUtil.sendHttpRequest(weatherUrl, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
System.out.println(response);
}
@Override
public void onError(Exception e) {
}
});
}
}
12.单元测试需在AndroidManifest.xml页面进行配置。
</application>标签上边:
<uses-library android:name="android.test.runner"/>
</manifest>标签上边:
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.example.weather"></instrumentation>
13.测试成功继续编写其他页面。util包下新建接口HttpCallbackListener.java页面,用作回调。
HttpCallbackListener.java页面:
package com.example.util;
public interface HttpCallbackListener {
void onFinish(String response);
void onError(Exception e);
}
14.adapter包下新建WeatherAdapter.java页面,作为处理处理天气数据源和ListView的适配器。
WeatherAdapter.java页面:
package com.example.adapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.model.Weather;
import com.example.weather.R;
public class WeatherAdapter extends ArrayAdapter<Weather> {
private int resourceId;
public WeatherAdapter(Context context, int textViewResourceId,
List<Weather> objects) {
super(context, textViewResourceId, objects);
resourceId = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Weather weather = getItem(position);
ViewHolder viewHolder = null;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(resourceId,
null);
viewHolder.tvDayOfWeek = (TextView) convertView
.findViewById(R.id.tvDayofWeek);
viewHolder.tvDate = (TextView) convertView
.findViewById(R.id.tvDate);
viewHolder.tvTemperature = (TextView) convertView
.findViewById(R.id.tvTemperature);
viewHolder.tvWeather = (TextView) convertView
.findViewById(R.id.tvWeather);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tvDayOfWeek.setText(weather.getDayOfWeek());
viewHolder.tvDate.setText(weather.getDate());
viewHolder.tvTemperature.setText(weather.getTemperature());
viewHolder.tvWeather.setText(weather.getWeather());
return convertView;
}
private class ViewHolder {
TextView tvDayOfWeek;
TextView tvDate;
TextView tvTemperature;
TextView tvWeather;
}
}
15.WeatherActivity.java页面获取URL并处理返回的数据。
WeatherActivity.java页面:
package com.example.weather;
import java.util.ArrayList;
import java.util.List;
import com.example.adapter.WeatherAdapter;
import com.example.get.HttpUtil;
import com.example.model.Weather;
import com.example.util.HttpCallbackListener;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.LayoutAnimationController;
import android.view.animation.ScaleAnimation;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
public class WeatherActivity extends Activity {
private EditText etCity;
private ImageButton btnQuery;
private ListView lvFutureWeather;
public static final int SHOW_RESPONSE = 1;
private List<Weather> data;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
if (response != null) {
parseWithJSON(response);
WeatherAdapter weatherAdapter = new WeatherAdapter(
WeatherActivity.this,
R.layout.activity_weather_listitem, data);
lvFutureWeather.setAdapter(weatherAdapter);
ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 0, 1);
scaleAnimation.setDuration(1000);
LayoutAnimationController animationController = new LayoutAnimationController(
scaleAnimation, 0.6f);
lvFutureWeather.setLayoutAnimation(animationController);
}
default:
break;
}
}
private void parseWithJSON(String response) {
data = new ArrayList<Weather>();
JsonParser parser = new JsonParser();// json 解析器
JsonObject obj = (JsonObject) parser.parse(response); /* 获取返回状态码 */
String resultcode = obj.get("resultcode").getAsString(); /* 如果状态码是200说明返回数据成功*/
if (resultcode != null && resultcode.equals("200")) {
JsonObject resultObj = obj.get("result").getAsJsonObject();
JsonArray futureWeatherArray = resultObj.get("future")
.getAsJsonArray();
for (int i = 0; i < futureWeatherArray.size(); i++) {
Weather weather = new Weather();
JsonObject weatherObject = futureWeatherArray.get(i)
.getAsJsonObject();
weather.setDayOfWeek(weatherObject.get("week")
.getAsString());
weather.setDate(weatherObject.get("date").getAsString());
weather.setTemperature(weatherObject.get("temperature")
.getAsString());
weather.setWeather(weatherObject.get("weather")
.getAsString());
data.add(weather);
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
initViews();
setListeners();
}
private void initViews() {
etCity = (EditText) findViewById(R.id.etCity);
btnQuery = (ImageButton) findViewById(R.id.btnQuery);
lvFutureWeather = (ListView) findViewById(R.id.lvFutureWeather);
}
private void setListeners() {
btnQuery.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String city = etCity.getText().toString();
Toast.makeText(WeatherActivity.this, "success",
Toast.LENGTH_LONG).show();
String weatherUrl = "http://v.juhe.cn/weather/index?format=2&cityname="+city+"&key=你自己的key";
HttpUtil.sendHttpRequest(weatherUrl,new HttpCallbackListener() {
@Override
public void onFinish(String response) {
Log.i("MainActivity","show");
Message message = new Message();
message.what = SHOW_RESPONSE; // 将服务器返回的结果存放到 Message 中
message.obj = response.toString();
handler.sendMessage(message);
Log.i("MainActivity","message:"+message);
}
@Override
public void onError(Exception e) {
System.out.println("访问失败");
}
});
}
});
}
}
16.运行就可以显示目标效果了。
17.源码:
点击打开链接
本文介绍如何在Android应用中动态显示输入城市后的天气信息。通过ListView展示未来几天的天气预报,实现输入城市名后点击按钮加载天气数据,并使用ListView动画效果增强用户体验。
5万+

被折叠的 条评论
为什么被折叠?



