1、项目效果图:

2、主页面MainActivity代码如下:

MainActivity.java

package com.qianfeng.weather;import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;import org.json.JSONObject;import java.util.ArrayList;
import java.util.List;public class MainActivity extends AppCompatActivity {private ImageView refreshIv;private ImageView searchIv;private TextView cityTv;private TextView pmTv;private TextView errorTv;private TextView tempTv;private TextView weatherTv;private TextView windTv;private TextView dateTv;private View lineView;private LinearLayout otherLl;private List<String> weekList;private Handler handler;private int code = 101100101;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();initData();getData(code);setListener();}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (requestCode == 100) {code = resultCode;getData(code);}}private void setListener() {refreshIv.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {getData(code);}});searchIv.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent intent = new Intent(MainActivity.this,SearchActivity.class);startActivityForResult(intent, 100);}});}/****/private void initData() {
//        在Android中借助handler类实现从服务器获取数据后更新UI页面(Handler原理)handler = new Handler() {@Overridepublic void handleMessage(Message msg) {if (msg.what == 200) {errorTv.setText((String) msg.obj);}if (msg.what == 100) {errorTv.setText("");
//                    停止转圈动画refreshIv.setBackgroundResource(R.mipmap.refresh);List<WeatherBean> list = (List<WeatherBean>) msg.obj;cityTv.setText(list.get(0).getCity());pmTv.setText(list.get(0).getPm());tempTv.setText(list.get(0).getTempCurrent());weatherTv.setText(list.get(0).getWeather() + " " + list.get(0).getTemp());windTv.setText(list.get(0).getWindCurrent());dateTv.setText(list.get(0).getDate_y() + " " + list.get(0).getWeek());if (list.get(0).getPm().substring(list.get(0).getPm().lastIndexOf(" ") + 1).equals("优")) {lineView.setBackgroundColor(getResources().getColor(R.color.pm1));} else if (list.get(0).getPm().substring(list.get(0).getPm().lastIndexOf(" ") + 1).equals("良")) {lineView.setBackgroundColor(getResources().getColor(R.color.pm2));} else if (list.get(0).getPm().substring(list.get(0).getPm().lastIndexOf(" ") + 1).equals("轻度污染")) {lineView.setBackgroundColor(getResources().getColor(R.color.pm3));} else if (list.get(0).getPm().substring(list.get(0).getPm().lastIndexOf(" ") + 1).equals("中度")) {lineView.setBackgroundColor(getResources().getColor(R.color.pm4));} else if (list.get(0).getPm().substring(list.get(0).getPm().lastIndexOf(" ") + 1).equals("重度")) {lineView.setBackgroundColor(getResources().getColor(R.color.pm5));} else if (list.get(0).getPm().substring(list.get(0).getPm().lastIndexOf(" ") + 1).equals("严重")) {lineView.setBackgroundColor(getResources().getColor(R.color.pm6));}
//                    清空水平滚动条的孙子辈视图otherLl.removeAllViews();
//                    将未来五天的天气信息动态设置到水平滚动条中的线性布局中的子视图中for (int i = 1; i < list.size(); i++) {View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, null);TextView weekItemTv = (TextView) view.findViewById(R.id.tv_week_item);TextView weatherItemTv = (TextView) view.findViewById(R.id.tv_weather_item);TextView tempItemTv = (TextView) view.findViewById(R.id.tv_temp_item);weekItemTv.setText(list.get(i).getWeek());weatherItemTv.setText(list.get(i).getWeather());tempItemTv.setText(list.get(i).getTemp());
//                        动态将item视图添加到otherLl中otherLl.addView(view);}}}};weekList = new ArrayList<>();weekList.add("星期一");weekList.add("星期二");weekList.add("星期三");weekList.add("星期四");weekList.add("星期五");weekList.add("星期六");weekList.add("星期日");}/*** 北京*/private void initView() {refreshIv = (ImageView) findViewById(R.id.refresh_iv);searchIv = (ImageView) findViewById(R.id.search_iv);cityTv = (TextView) findViewById(R.id.city_tv);pmTv = (TextView) findViewById(R.id.pm_tv);errorTv = (TextView) findViewById(R.id.error_tv);tempTv = (TextView) findViewById(R.id.temp_tv);weatherTv = (TextView) findViewById(R.id.weather_tv);windTv = (TextView) findViewById(R.id.wind_tv);dateTv = (TextView) findViewById(R.id.date_tv);lineView = findViewById(R.id.line_view);otherLl = (LinearLayout) findViewById(R.id.other_ll);}/*** 获取网络数据*/private void getData(final int code) {if (!NetUtils.isActive(MainActivity.this)) {errorTv.setText("请确认是否有网");Toast.makeText(MainActivity.this, "亲,确认您是否有网!", Toast.LENGTH_LONG).show();return;}refreshIv.setBackgroundResource(R.drawable.pb_bg);//封装 继承  多态AnimationDrawable animationDrawable = (AnimationDrawable) refreshIv.getBackground();animationDrawable.start();//        开一个子线程进行网络请求  获取服务器json数据(注意:Android主线程不能操作耗时代码块)new Thread(new Runnable() {@Overridepublic void run() {String uri = "http://weather.123.duba.net/static/weather_info/" + code + ".html";String result = NetUtils.doGet(uri);
//                list集合中存的今天+未来五天的天气信息List<WeatherBean> list = parserJson(result);Message message = handler.obtainMessage();
//                集合数据为空时让其检查网络问题,或请程序员核查代码(未彻底优化代码结构以及代码性能等)if (list == null || list.size() == 0) {message.what = 200;message.obj = "请检查网络";handler.sendMessage(message);return;}message.what = 100;message.obj = list;handler.sendMessage(message);
//                注意:子线程不能更新UI主线程的页面
//                cityTv.setText(list.get(0).getCity());}}).start();}/*** 解析json数据** @param result*/private List<WeatherBean> parserJson(String result) {List<WeatherBean> list = new ArrayList<>();try {JSONObject jsonObject = new JSONObject(result);JSONObject weatherInfo = jsonObject.getJSONObject("weatherinfo");
//            保存今天+未来五天的天气数据for (int i = 1; i < 7; i++) {WeatherBean weatherBean = new WeatherBean();if (i == 1) {weatherBean.setCity(weatherInfo.getString("city"));weatherBean.setCityId(weatherInfo.getString("cityid"));weatherBean.setDate_y(weatherInfo.getString("date_y"));weatherBean.setPm("PM:" + weatherInfo.getString("pm") + " " + weatherInfo.getString("pm-level"));weatherBean.setTempCurrent(weatherInfo.getString("temp") + "°");weatherBean.setWindCurrent(weatherInfo.getString("wd") + " " + weatherInfo.getString("ws"));}weatherBean.setWeek(getWeek(i, weatherInfo.getString("week")));weatherBean.setTemp(weatherInfo.getString("temp" + i));weatherBean.setWeather(weatherInfo.getString("weather" + i));
//                将每天的天气信息保存到集合中list.add(weatherBean);}return list;} catch (Exception e) {e.printStackTrace();return null;}}/*** @param i* @param week* @return*/private String getWeek(int i, String week) {int index = 0;for (int j = 0; j < weekList.size(); j++) {if (weekList.get(j).equals(week)) {index = j;break;
//                continue;}}if (index + i < 8) {index = index + i - 1;} else {index = index + i - 8;}return weekList.get(index);}
}

NetUtils(网络工具类):

package com.qianfeng.weather;import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;public class NetUtils {/*** 监测是否有网*/public static boolean isActive(Context context) {ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo info = manager.getActiveNetworkInfo();if (info != null) {return info.isConnected();}return false;}/*** 根据传过来的接口地址,返回服务器吐出来的字符串*/public static String doGet(String uri) {StringBuffer stringBuffer = new StringBuffer();String result = null;URLConnection connection = null;InputStream inputStream = null;try {URL url = new URL(uri);connection = url.openConnection();connection.setConnectTimeout(10 * 1000);inputStream = connection.getInputStream();BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));String line = bufferedReader.readLine();while (line != null) {stringBuffer.append(line);line = bufferedReader.readLine();}result = stringBuffer.substring(stringBuffer.indexOf("(") + 1, stringBuffer.lastIndexOf(")"));return result;} catch (Exception e) {e.printStackTrace();return null;}}}

WeatherBean.java

package com.qianfeng.weather;public class WeatherBean {private String city;private String cityId;private String week;private String temp;private String date_y;private String wind;private String weather;private String pm;private String tempCurrent;private String windCurrent;public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getCityId() {return cityId;}public void setCityId(String cityId) {this.cityId = cityId;}public String getWeek() {return week;}public void setWeek(String week) {this.week = week;}public String getTemp() {return temp;}public void setTemp(String temp) {this.temp = temp;}public String getDate_y() {return date_y;}public void setDate_y(String date_y) {this.date_y = date_y;}public String getWind() {return wind;}public void setWind(String wind) {this.wind = wind;}public String getWeather() {return weather;}public void setWeather(String weather) {this.weather = weather;}public String getPm() {return pm;}public void setPm(String pm) {this.pm = pm;}public String getTempCurrent() {return tempCurrent;}public void setTempCurrent(String tempCurrent) {this.tempCurrent = tempCurrent;}public String getWindCurrent() {return windCurrent;}public void setWindCurrent(String windCurrent) {this.windCurrent = windCurrent;}
}

3、主页面XML布局如下:

activity_main.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:background="@mipmap/background"><ImageViewandroid:id="@+id/refresh_iv"android:layout_width="40dp"android:layout_height="40dp"android:layout_margin="12dp"android:background="@mipmap/refresh" /><ImageViewandroid:id="@+id/search_iv"android:layout_width="40dp"android:layout_height="40dp"android:layout_alignParentRight="true"android:layout_margin="12dp"android:background="@mipmap/search" /><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_marginTop="12dp"android:gravity="center_horizontal"android:orientation="vertical"><TextViewandroid:id="@+id/city_tv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textColor="#FFF"android:textSize="28sp" /><TextViewandroid:id="@+id/pm_tv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textColor="#FFF"android:textSize="20sp" /><Viewandroid:id="@+id/line_view"android:layout_width="match_parent"android:layout_height="10dp"android:background="#6BCD07" /><TextViewandroid:id="@+id/error_tv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textColor="#F00"android:textSize="20sp" /></LinearLayout><RelativeLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerVertical="true"android:layout_marginLeft="12dp"><TextViewandroid:id="@+id/temp_tv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textColor="#FFF"android:textSize="40sp" /><!--android:layout_alignBaseline="@+id/temp_tv"android:layout_alignBottom="@+id/temp_tv"--><TextViewandroid:id="@+id/weather_tv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBottom="@+id/temp_tv"android:layout_toRightOf="@+id/temp_tv"android:textColor="#FFF" /><TextViewandroid:id="@+id/wind_tv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/temp_tv"android:textColor="#FFF" /><TextViewandroid:id="@+id/date_tv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/wind_tv"android:textColor="#FFF" /></RelativeLayout><!--直接的子孩子只能有一个,但是可以有很多的孙子--><HorizontalScrollViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"><LinearLayoutandroid:id="@+id/other_ll"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="#6666"android:orientation="horizontal"></LinearLayout></HorizontalScrollView>
</RelativeLayout>

item.xml(用在Java代码动态加载后五天天气信息Item小布局):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center_horizontal"android:orientation="vertical"android:paddingLeft="5dp"android:paddingRight="5dp"><TextViewandroid:id="@+id/tv_week_item"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="12dp"android:layout_marginBottom="12dp"android:text="星期三"android:textColor="#FFF"android:textSize="18sp" /><TextViewandroid:id="@+id/tv_weather_item"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="多云"android:textColor="#FFF"android:textSize="18sp" /><TextViewandroid:id="@+id/tv_temp_item"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="12dp"android:layout_marginBottom="12dp"android:text="20°C~29°C"android:textColor="#FFF"android:textSize="16sp" /></LinearLayout>

4、搜索页面实现SearchActivity.java,主要包含XML解析,具体代码如下:

SearchActivity.java

package com.qianfeng.weather;import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;import java.io.IOException;
import java.io.InputStream;
import java.util.Map;public class SearchActivity extends AppCompatActivity {private EditText auto = null;private Map<String, String> map = null;private ImageView iv_search = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_search);initData();initView();}private void initView() {auto = (EditText) findViewById(R.id.autoTV);iv_search = (ImageView) findViewById(R.id.iv_search);iv_search.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String city = auto.getText().toString().trim();String codeStr = map.get(city);if (codeStr != null) {int code = Integer.parseInt(codeStr);SearchActivity.this.setResult(code);finish();} else {auto.setText("中国没有这样的城市,请重新输入"+ "或"+ "输入内容不能为空");}}});}private void initData() {try {InputStream is = getAssets().open("city_code.xml");map = new XMLParser().getMap(is);} catch (IOException e) {e.printStackTrace();}}
}

XMLParser(XML解析工具类)

package com.qianfeng.weather;import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;import static java.net.Proxy.Type.HTTP;public class XMLParser {/***xml解析  pull  sax 。。。*/public Map<String, String> getMap(InputStream is) {Map<String, String> map = new HashMap<>();try {XmlPullParserFactory factory = XmlPullParserFactory.newInstance();XmlPullParser parser = factory.newPullParser();parser.setInput(new BufferedReader(new InputStreamReader(is)));
//            parser.setInput(is,null);
//            XmlPullParser.END_DOCUMENT
//            XmlPullParser.START_DOCUMENT
//            XmlPullParser.START_TAG
//            XmlPullParser.END_TAG
//            XmlPullParser.TEXTint eventType = parser.getEventType();while (eventType != XmlPullParser.END_DOCUMENT) {if (eventType == XmlPullParser.START_TAG) {String name = parser.getName();if ("key".equals(name)) {String key = parser.nextText();parser.next();parser.next();String value = parser.nextText();map.put(key, value);}}parser.next();eventType = parser.getEventType();}} catch (Exception e) {e.printStackTrace();}return map;}
}

activity_search.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:background="@mipmap/background"android:padding="5dp"android:orientation="vertical" ><!-- 搜索 --><ImageViewandroid:id="@+id/iv_search"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_marginRight="17dp"android:src="@mipmap/search" /><EditTextandroid:id="@+id/autoTV"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentEnd="true"android:layout_alignParentRight="true"android:layout_marginEnd="41dp"android:layout_marginRight="41dp"android:hint="请输入城市" /></RelativeLayout>

5、AndroidManifest清单文件如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.qianfeng.weather"><!--访问网络状态权限--><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><!--访问Internet网络权限--><uses-permission android:name="android.permission.INTERNET" /><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".SearchActivity"></activity><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

7、加载网络不好转圈动画用的自定义帧动画pb_bg.xml,具体代码如下:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" ><itemandroid:drawable="@mipmap/pb00"android:duration="200"/><itemandroid:drawable="@mipmap/pb01"android:duration="200"/><itemandroid:drawable="@mipmap/pb02"android:duration="200"/><itemandroid:drawable="@mipmap/pb03"android:duration="200"/><itemandroid:drawable="@mipmap/pb04"android:duration="200"/><itemandroid:drawable="@mipmap/pb05"android:duration="200"/><itemandroid:drawable="@mipmap/pb06"android:duration="200"/><itemandroid:drawable="@mipmap/pb07"android:duration="200"/><itemandroid:drawable="@mipmap/pb08"android:duration="200"/><itemandroid:drawable="@mipmap/pb09"android:duration="200"/><itemandroid:drawable="@mipmap/pb10"android:duration="200"/><itemandroid:drawable="@mipmap/pb11"android:duration="200"/>
</animation-list>

6、资源图片等具体代码可参考本人共享发送上传代码资源Weather.zip

Android天气预报项目相关推荐

  1. android天气预报项目总结报告,Android项目:天气预报App

    一 介绍 该项目是在Android Studio的环境下实现的,主要是仿照了小米10手机上的天气预报App. 二 效果图 三 页面介绍 1.主界面                            ...

  2. android天气预报实训程序清单,Android天气预报项目

    1.项目效果图: 2.主页面MainActivity代码如下: MainActivity.java package com.qianfeng.weather; import android.conte ...

  3. android天气预报项目源代码下载,Android适合新手学习的天气预报项目代码

    天气信息界面包含了温度,日出,风力,降水概率,发布时间等信息,此外还有当天某个时间点的天气预测信息,以ListView组件呈现.两个按钮也是提供了重新选择城市以及更新天气信息的功能. 1. com.c ...

  4. Android 开源项目集合

    2019独角兽企业重金招聘Python工程师标准>>> 上百个Android开源项目分享,希望对android开发有帮助. Android PDF 阅读器 http://source ...

  5. 上百个Android开源项目分享

    转载地址:[http://blog.csdn.net/bboyfeiyu/article/details/12234163] 上百个Android开源项目分享,希望对android开发有帮助. And ...

  6. Android开源项目大合集(转载的基础上添加了项目地址)

    WeChat高仿微信 项目地址:https://github.com/motianhuo/wechat 高仿微信,实现功能有: 好友之间文字聊天,表情,视频通话,语音,语音电话,发送文件等. 知乎专栏 ...

  7. 381个Android开源项目

    ├─地图相关 Android bikeroute自行车导航源码.rar: http://www.t00y.com/file/64335654 Android Gps Test源码.rar: http: ...

  8. android开源项目 Google code

    173个Android项目源码:  http://mobile.51cto.com/abased-402933.htm       下载地址:http://asksong.ctfile.com/fil ...

  9. 好的android开源项目

    转载:http://www.apkbus.com/android-17627-1-1.html Android开发又将带来新一轮热潮,很多开发者都投入到这个浪潮中去了,创造了许许多多相当优秀的应用.其 ...

最新文章

  1. ADF_ManagedBean的概念和管理(概念)
  2. Final Cut Pro快捷键
  3. UVA 10196 Check The Check(模拟)
  4. java 数组怎么求和_java数组排序,并将数组内的数据求和
  5. beaglebone black 联网
  6. postman安装_Postman插件的应用与实战(二)
  7. FileDescriptor的作用
  8. 为使节构建控制平面的指南第3部分-特定于域的配置API
  9. Halcon学习笔记:xyz_attrib_to_object_model_3d示例
  10. canal mysql5.6_超详细的Canal入门,看这篇就够了!
  11. 自动根据键盘位置调整UITextView的高度
  12. Oracle与SQL Server的语法区别——Oracle数据库学习
  13. 音频管理工具- Realtek 高清音频管理器
  14. jsp综合开发实例——夏日九宫格日记网
  15. STM32F1 W5500 TCP Client 回环测试
  16. 英文字母注册商标的最全攻略来了
  17. 计算机启动后桌面上什么都没有,电脑开机后,桌面上什么都没有了?我怎么处理?好着急啊...
  18. mysql 谓语提前,谓语提前的倒装句:
  19. java-net-php-python-ssm车辆保养管理系统计算机毕业设计程序
  20. skywalking安装

热门文章

  1. 【Rust 日报】2021-11-11 保持冷静,学习Rust,我们很快就会在Linux中更多的看到这种语言...
  2. win32 透明窗口无边框模版
  3. Photo2Cartoon,照片图片批量转漫画
  4. xiuno开发文档_大白 · TinyMCE编辑器v1.9_Xiuno Plugin_奇狐插件商店_奇狐网
  5. 微信公众号如何和Salesforce集成,然后后台给公众号的关注者推送模板消息?
  6. 关于 Kubernetes中Service的一些笔记
  7. Android 中短信数据库的简单操作
  8. python的requests爬取Uniprot中蛋白序列和N-糖基化位点
  9. 《现代密码学》学习笔记——第三章 分组密码 [三]分组密码的运行模式
  10. 微软 Office 全家桶被 GPT-4 革新:Word 一键变成 PPT,打工人的春天来了!