編輯:關於 Android 程式設計
之前做過一版天氣預報,功能勉強跑通,但界面實在太醜,所以上一篇博客連截圖都沒好意思放。這一版做了兩件事:一是重做了界面,二是從只能看實時天氣擴展到了未來七天預報。
先看前後對比:


順帶說一下項目背景:這是寫給楊凌一位閨蜜的,一半是逗她開心,一半是練手。所以中間那塊提示文字並不是常規的穿衣建議,而是我自己寫的一些話,你完全可以替換成任何內容。
新建項目之後,因為要聯網,先導入網絡包並申請權限。
依賴配置:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.1'
compile files('libs/httpclient-4.4.1.jar')
compile files('libs/httpcore-4.4.1.jar')
}
後面兩個 http 包就是這次要用的網絡庫。引入它們的同時,還必須加上一段 packagingOptions,否則會報重複文件衝突:
packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/dependencies.txt'
exclude 'META-INF/LGPL2.1'
}
Manifests 中,在 application 標籤之外添加:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
這樣基本准備就完成了,能在後續編碼時少踩很多坑。
我的佈局寫得比較樸素,基本都是最簡單的控件,展示主要依賴 TextView。先貼代碼,後面引用 id 時還要回來查:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/back"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@mipmap/sunny_overcast"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="40dp" />
<!-- 城市名 -->
<TextView
android:id="@+id/city"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="楊凌"
android:textSize="40dp" />
<!-- 實時天氣 -->
<TextView
android:id="@+id/weather_day"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="happy"
android:textSize="20dp" />
<!-- 實時溫度 -->
<TextView
android:id="@+id/wendu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="15"
android:textSize="90dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#ffffff" />
<!-- 中間自定義的提示文字 -->
<TextView
android:id="@+id/remind"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:textSize="20dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#ffffff" />
<!-- 未來七天:七行結構完全一致,id 分別為 la~lg,
每行為「星期 + 天氣圖標 + 最高溫 + 最低溫」。
下面給出一行的完整寫法,其餘六行按同樣模式複製,
把 day_xxx / image_xxx / high_xxx / low_xxx 換成
two、three、four、five、six、seven 即可 -->
<LinearLayout
android:id="@+id/la"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.2" />
<TextView
android:id="@+id/day_one"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:text="星期"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5" />
<TextView
android:id="@+id/image_one"
android:layout_width="80dp"
android:layout_height="fill_parent"
android:layout_gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5" />
<TextView
android:id="@+id/high_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="high" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5" />
<TextView
android:id="@+id/low_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="low" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5" />
</LinearLayout>
<!-- lb / lc / ld / le / lf / lg 同上 -->
<TextView
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#ffffff" />
<TextView
android:layout_width="fill_parent"
android:layout_height="5dp" />
<!-- 底部:城市輸入與切換按鈕 -->
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.2" />
<EditText
android:id="@+id/serach_city"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_weight="3"
android:background="@drawable/shape"
android:hint="Input City"
android:text="楊凌"
android:textColorHint="#ee9999"
android:textSize="20dp" />
<Button
android:id="@+id/change"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:background="@drawable/btn"
android:text="切換城市"
android:textSize="20dp" />
</LinearLayout>
</LinearLayout>
需要說明的是,原本我還准備做下拉刷新,所以外層本來套了 SwipeRefreshLayout,但最終沒用上,把這個控件去掉也完全可行。另外因為閨蜜在楊凌,輸入框的初始值就寫死了「楊凌」。
整個項目只有一個 Activity。先貼完整代碼:
package com.example.katherine_qj.dayweather;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends Activity {
private TextView city, weather_day, wendu, remind;
private EditText search_city;
private Button change;
private TextView day_one, image_one, high_one, low_one;
private TextView day_two, image_two, high_two, low_two;
private TextView day_three, image_three, high_three, low_three;
private TextView day_four, image_four, high_four, low_four;
private TextView day_five, image_five, high_five, low_five;
private TextView day_six, image_six, high_six, low_six;
private TextView day_seven, image_seven, high_seven, low_seven;
private LinearLayout bei, la, lb, lc, ld, le, lf, lg;
private static Handler handler; // 未來天氣
private static Handler handler_now; // 實時天氣
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Init(); // 初始化所有控件
if (!isNetworkConnected()) {
Toast toast = Toast.makeText(getApplicationContext(),
"寶寶你手機沒有網", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
// 兩個線程同時啟動:一個查實時天氣,一個查未來天氣
startWeatherThreads();
// 點擊「切換城市」重新請求
change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startWeatherThreads();
}
});
}
private void startWeatherThreads() {
handler = new Myhandler();
handler_now = new Myhandler_now();
new Thread(new Weather_Thread()).start();
new Thread(new Weather_now_Thread()).start();
}
/** 網絡請求工具方法:傳入接口地址,返回響應字符串 */
public static String getURLConnection(String path) {
StringBuilder xml = new StringBuilder();
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(path);
HttpResponse response = client.execute(get);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream reader = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(reader));
String line = buffer.readLine();
while (line != null) {
xml.append(line);
line = buffer.readLine();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return xml.toString();
}
/** 未來七天預報線程 */
public class Weather_Thread implements Runnable {
public void run() {
String first = "https://api.k780.com:88/?app=weather.future&weaid=";
String cityName = search_city.getText().toString().trim();
String last = "&&appkey=18276&sign=3f3716462bb4ed68bd082761c3602509&format=json";
String result = getURLConnection(first + cityName + last);
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("Weather", result);
msg.setData(bundle);
handler.sendMessage(msg);
}
}
/** 實時天氣線程 */
public class Weather_now_Thread implements Runnable {
public void run() {
String first = "https://api.k780.com:88/?app=weather.today&weaid=";
String cityName = search_city.getText().toString().trim();
String last = "&&appkey=18276&sign=3f3716462bb4ed68bd082761c3602509&format=json";
String result = getURLConnection(first + cityName + last);
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("Weather_now", result);
msg.setData(bundle);
handler_now.sendMessage(msg);
}
}
/** 解析實時天氣 */
public class Myhandler_now extends Handler {
public void handleMessage(Message msg) {
String json = msg.getData().getString("Weather_now");
if (json == null || json.equals("")) return;
try {
JSONObject result = new JSONObject(json).getJSONObject("result");
city.setText(result.getString("citynm"));
weather_day.setText(result.getString("weather"));
wendu.setText(result.getString("temperature_curr"));
Init(result.getString("week"));
Init_Image(result.getString("weather"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** 解析未來七天預報 */
public class Myhandler extends Handler {
public void handleMessage(Message msg) {
String json = msg.getData().getString("Weather");
if (json == null || json.equals("")) return;
try {
JSONArray array = new JSONObject(json).getJSONArray("result");
for (int i = 0; i < array.length() && i < 7; i++) {
JSONObject item = array.getJSONObject(i);
String week = item.getString("week");
String wea = item.getString("weather");
String high = item.getString("temp_high") + "°";
String low = item.getString("temp_low") + "°";
switch (i) {
case 0: setDay(day_one, image_one, high_one, low_one, week, wea, high, low); break;
case 1: setDay(day_two, image_two, high_two, low_two, week, wea, high, low); break;
case 2: setDay(day_three, image_three, high_three, low_three, week, wea, high, low); break;
case 3: setDay(day_four, image_four, high_four, low_four, week, wea, high, low); break;
case 4: setDay(day_five, image_five, high_five, low_five, week, wea, high, low); break;
case 5: setDay(day_six, image_six, high_six, low_six, week, wea, high, low); break;
case 6: setDay(day_seven, image_seven, high_seven, low_seven, week, wea, high, low); break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setDay(TextView day, TextView img, TextView h, TextView l,
String week, String wea, String high, String low) {
day.setText(week);
img.setText(wea);
h.setText(high);
l.setText(low);
}
}
/** 根據天氣切換背景圖 */
public void Init_Image(String str) {
if (str.equals("晴")) {
bei.setBackgroundResource(R.mipmap.sunny);
} else if (str.equals("多雲轉小雨") || str.equals("小雨轉多雲") || str.equals("小雨")) {
bei.setBackgroundResource(R.mipmap.light_rain);
} else if (str.equals("多雲轉晴") || str.equals("晴轉多雲") || str.equals("多雲轉陰")
|| str.equals("陰轉多雲") || str.equals("多雲")) {
bei.setBackgroundResource(R.mipmap.cloudy);
} else {
bei.setBackgroundResource(R.mipmap.frost);
}
Init_T();
}
/** 給七行預報加上半透明效果 */
public void Init_T() {
la.getBackground().setAlpha(100);
lb.getBackground().setAlpha(100);
lc.getBackground().setAlpha(100);
ld.getBackground().setAlpha(100);
le.getBackground().setAlpha(100);
lf.getBackground().setAlpha(100);
lg.getBackground().setAlpha(100);
}
/** 中間提示文字:按星期顯示不同內容 */
public void Init(String week) {
if (week.equals("星期一")) {
remind.setText("水力學,水文地質學,工程結構,馬克思主義基本原理");
} else if (week.equals("星期二")) {
remind.setText("地理信息系統,工程測量,工程結構");
} else if (week.equals("星期三")) {
remind.setText("工程結構,地理信息系統,水文地質學,水力學");
} else if (week.equals("星期四")) {
remind.setText("工程結構,工程測量,水力學,馬克思主義基本原理");
} else if (week.equals("星期五")) {
remind.setText("體育,水力學");
} else if (week.equals("星期六")) {
remind.setText("寶寶今天是周六,好好休息,看看電視想想我");
} else if (week.equals("星期日")) {
remind.setText("寶寶今天是周末,明天就是星期一了,今天你該去運動的!愛你愛你");
} else {
remind.setText("寶寶你要是看到這句話,就證明世界末日了!!!!!!");
}
}
/** 初始化所有控件 */
public void Init() {
city = (TextView) findViewById(R.id.city);
weather_day = (TextView) findViewById(R.id.weather_day);
wendu = (TextView) findViewById(R.id.wendu);
remind = (TextView) findViewById(R.id.remind);
change = (Button) findViewById(R.id.change);
search_city = (EditText) findViewById(R.id.serach_city);
day_one = (TextView) findViewById(R.id.day_one);
image_one = (TextView) findViewById(R.id.image_one);
high_one = (TextView) findViewById(R.id.high_one);
low_one = (TextView) findViewById(R.id.low_one);
// ... two ~ seven 依此類推
bei = (LinearLayout) findViewById(R.id.back);
la = (LinearLayout) findViewById(R.id.la);
lb = (LinearLayout) findViewById(R.id.lb);
lc = (LinearLayout) findViewById(R.id.lc);
ld = (LinearLayout) findViewById(R.id.ld);
le = (LinearLayout) findViewById(R.id.le);
lf = (LinearLayout) findViewById(R.id.lf);
lg = (LinearLayout) findViewById(R.id.lg);
}
/** 判斷網絡是否可用 */
public boolean isNetworkConnected() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnectedOrConnecting();
}
}
我讀程序的習慣是從 onCreate 入手,所以我們一起看它的執行路徑:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Init(); // 初始化控件
if (!isNetworkConnected()) { // 檢查網絡
// 沒網就提示一下
}
startWeatherThreads(); // 啟動兩個線程並綁定 Handler
change.setOnClickListener(...); // 切換城市時重新請求
}
總結起來就是三步:初始化控件、啟動線程、綁定事件。
兩個線程的結構完全一樣,區別只在接口地址和解析方式。以未來天氣為例:
public class Weather_Thread implements Runnable {
public void run() {
String first = "https://api.k780.com:88/?app=weather.future&weaid=";
String cityName = search_city.getText().toString().trim();
String last = "&&appkey=18276&sign=3f3716462bb4ed68bd082761c3602509&format=json";
// getURLConnection 是自己封裝的網絡訪問方法:傳入接口,返回字符串
String result = getURLConnection(first + cityName + last);
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("Weather", result);
msg.setData(bundle);
handler.sendMessage(msg);
}
}
這裡的關鍵是 Handler 消息機制:網絡請求是耗時操作,必須放在子線程;而拿到數據後要更新界面,又必須回到主線程。所以子線程只負責取數據,通過 Handler 把字符串拋給主線程處理。
未來天氣返回的是一個數組,需要遍歷後逐項填充;實時天氣則是一個對象,取值更直接。
JSONArray array = new JSONObject(json).getJSONArray("result");
for (int i = 0; i < array.length() && i < 7; i++) {
JSONObject item = array.getJSONObject(i);
// week / weather / temp_high / temp_low 分別填入對應的 TextView
}
說白了就是「通過鍵取對應的值」,再按數組長度循環取出每一項顯示。實時天氣的解析邏輯相同,只是少了一層循環。
另外提一句:代碼裡還留著一些 Log 和 System.out,是我調試時沒刪乾淨的,實際使用時清理掉即可。
Android Notification 通知實作大全:三種版本寫法與自訂版面
手機收到簡訊時,即便沒有點開,最上方狀態列也會出現一個小圖示提示——這就是 Notification 的效果。本文整理三種不同 API 時期的通知建立方式,並示範自訂通知
Android Matrix 源碼透視:從數學原理到代碼驗證
只要做過圖片處理,你一定用過 Matrix。Android 中的 Matrix 本質上是一個 3 × 3 的矩陣: 它對圖像的處理可以歸納為四類基本變換: Tr
Android 靈活佈局:用 XML 檔取代拖拉排版
一開始接觸 Android 時,我只會用拖拉的方式排版,既死板又難看。後來才發現,原來它和 JSP 一樣,可以靈活地使用 XML 檔來定義佈局,效果立刻大為改善。 話不多
Android 動畫全景解析:View 動畫、幀動畫與屬性動畫
動畫是面試高頻考點,也是提升產品質感的關鍵。Android 動畫分三大類,先建立整體認知: View 動畫(補間動畫):通過平移、縮放、旋轉、透明度變化做漸進式變換。