編輯:關於 Android 程式設計
本系列前一篇已經用 Fragment 的方式做過一次 TabHost,這次換一條路:直接讓 MainActivity 繼承 TabActivity,用更傳統的寫法把主界面的四個頁籤搭起來,同時把微博 API 的請求與解析抽成一個工具類。
思路很直白:每個頁籤的內容就是一個獨立的 Activity,底部再放一組 RadioButton 作為「假 tab」,讓點擊事件去驅動真正的 TabHost 切換。
public class MainActivity extends TabActivity {
private TabHost tabHost;
private static final String HOME_TAB = "home";
private static final String AT_TAB = "at";
private static final String MSG_TAB = "msg";
private static final String MORE_TAB = "more";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tabHost = getTabHost();
TabSpec homeSpec = tabHost.newTabSpec(HOME_TAB)
.setIndicator(HOME_TAB)
.setContent(new Intent(this, HomeActivity.class));
TabSpec atSpec = tabHost.newTabSpec(AT_TAB)
.setIndicator(AT_TAB)
.setContent(new Intent(this, AtActivity.class));
TabSpec msgSpec = tabHost.newTabSpec(MSG_TAB)
.setIndicator(MSG_TAB)
.setContent(new Intent(this, MsgActivity.class));
TabSpec moreSpec = tabHost.newTabSpec(MORE_TAB)
.setIndicator(MORE_TAB)
.setContent(new Intent(this, MoreActivity.class));
tabHost.addTab(homeSpec);
tabHost.addTab(atSpec);
tabHost.addTab(msgSpec);
tabHost.addTab(moreSpec);
tabHost.setCurrentTabByTag(HOME_TAB);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.main_radio);
final RadioButton rb = (RadioButton) findViewById(R.id.rb_home);
rb.setBackgroundResource(R.drawable.tabhost_press);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// 先把所有按鈕恢復常態,再由下面分支高亮當前項
rb.setBackgroundResource(R.drawable.tabhost_bg_selector);
switch (checkedId) {
case R.id.rb_home:
tabHost.setCurrentTabByTag(HOME_TAB);
break;
case R.id.rb_at:
tabHost.setCurrentTabByTag(AT_TAB);
break;
case R.id.rb_mess:
tabHost.setCurrentTabByTag(MSG_TAB);
break;
case R.id.rb_more:
tabHost.setCurrentTabByTag(MORE_TAB);
break;
default:
break;
}
}
});
}
}
這裡有兩個容易踩坑的細節:TabHost、TabWidget、FrameLayout 的 id 必須使用系統預定義的 @android:id/...,不能自訂;而 TabWidget 要設為 gone,因為真正的頁籤樣式由底部的 RadioGroup 呈現。
<TabHost xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<RadioGroup
android:id="@+id/main_radio"
android:layout_width="fill_parent"
android:layout_height="48dp"
android:layout_gravity="bottom"
android:background="@drawable/bar"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@drawable/home_icon"
android:text="首頁" />
<RadioButton
android:id="@+id/rb_at"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@drawable/at_icon"
android:text="我" />
<RadioButton
android:id="@+id/rb_mess"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@drawable/msg_icon"
android:text="消息" />
<RadioButton
android:id="@+id/rb_more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@drawable/more_icon"
android:text="更多" />
</RadioGroup>
</TabHost>
四個 Activity 各自承擔一個頁籤的內容,後續只要在對應的 Activity 裡針對性地把介面寫完即可。
這個類只做三件事:發 HTTP 請求、解析 JSON、把結果裝進 bean。由於專案裡到處都要發請求,我把最通用的那一小段抽成了獨立方法 HttpRequest,避免每個介面都重複一遍。目前只實作了「讀取自己所關注好友的微博列表」。
package com.fangjie.weibo.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.fangjie.weibo.bean.User;
import com.fangjie.weibo.bean.Weibo;
public class WeiboUtil {
/** 取得首頁時間線(關注的人) */
public List<Weibo> getWeiboList(String token, long maxId) {
List<Weibo> weibos = new ArrayList<Weibo>();
String url = "https://api.weibo.com/2/statuses/home_timeline.json";
String params = "access_token=" + token + "&max_id=" + maxId;
String result = HttpRequest(1, url, params);
try {
JSONObject jsonRes = new JSONObject(result);
JSONArray jsonWeibos = jsonRes.getJSONArray("statuses");
for (int j = 0; j < jsonWeibos.length(); j++) {
JSONObject jsonWeibo = jsonWeibos.getJSONObject(j);
Weibo weibo = new Weibo();
// 這裡省略 id、text、createdAt 等欄位的取值
JSONObject jsonUser = jsonWeibo.getJSONObject("user");
User user = new User();
// 這裡省略 user 的 id、screenName、profileImageUrl 等欄位
weibo.setUser(user);
// 轉發微博:只有原微博存在時才解析
if (jsonWeibo.has("retweeted_status")) {
JSONObject jsonZWeibo = jsonWeibo.getJSONObject("retweeted_status");
Weibo zWeibo = new Weibo();
JSONObject jsonZUser = jsonZWeibo.getJSONObject("user");
User zUser = new User();
zWeibo.setUser(zUser);
weibo.setRetweetedStatus(zWeibo);
}
weibos.add(weibo);
}
} catch (Exception e) {
e.printStackTrace();
}
return weibos;
}
/**
* 通用 HTTP 請求方法
* @param way 0 表示 POST,1 表示 GET
*/
public static String HttpRequest(int way, String urlStr, String params) {
String result = "";
BufferedReader in = null;
PrintWriter out = null;
try {
URL realUrl = new URL(urlStr);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 4.0; Windows NT)");
connection.setRequestProperty("Accept", "*/*");
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
if (way == 0) { // POST
connection.setDoOutput(true);
out = new PrintWriter(connection.getOutputStream());
out.print(params);
out.flush();
}
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) in.close();
} catch (Exception ignored) { }
if (out != null) out.close();
}
return result;
}
}
把請求細節集中到一個方法之後,各個 Activity 只需要關心「要哪份資料」和「怎麼顯示」,程式碼的可讀性會好很多。
歡迎關注我的個人站點:https://fangjie.sinaapp.com/
Android 視頻處理:為錄製影片加入動態時間水印
在部分影音應用中,需求不只是畫面上顯示時間,而是要把時間資訊直接燒錄進影片畫面。這代表影片在電腦或其他裝置播放時,也能看到每一段畫面的時間標記。本文整理在 Android
Android 筆記(24):用 WebView 打造白天/夜間閱讀模式
前言 這一篇想跟大家分享一個 WebView 的實用案例——透過 Android 呼叫 JavaScript 來切換頁面的白天與夜間模式。至於 WebView 的基本用法
自製跳動小球動畫:屬性動畫+貝茲曲線+SurfaceView 的組合練習
過去我對複雜動畫與進階 UI 涉入不深,直到前陣子在一個 Android 技術影片裡看到動腦學院的公開課,講的是載入動畫,長達 160 分鐘,我硬是用手機看完了。邊看邊
百度地圖圖層玩法:普通圖、衛星圖、實時路況與城市熱力圖
一張地圖不只有「地圖」這一種樣貌。切換衛星影像、疊加實時路況、顯示城市熱力分布——這些效果在百度地圖 Android SDK 裡都只要一行屬性設定就能搞定。本文帶你看懂