Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

新浪微博 Android 客戶端實戰(五):TabActivity 搭建主界面與 WeiboUtil 網路封裝

編輯:關於 Android 程式設計

本系列前一篇已經用 Fragment 的方式做過一次 TabHost,這次換一條路:直接讓 MainActivity 繼承 TabActivity,用更傳統的寫法把主界面的四個頁籤搭起來,同時把微博 API 的請求與解析抽成一個工具類。

一、用 TabActivity 實現主界面

思路很直白:每個頁籤的內容就是一個獨立的 Activity,底部再放一組 RadioButton 作為「假 tab」,讓點擊事件去驅動真正的 TabHost 切換。

MainActivity.java

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;
                }
            }
        });
    }
}

布局檔 main.xml

這裡有兩個容易踩坑的細節: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 裡針對性地把介面寫完即可。

二、WeiboUtil:請求、解析、封裝

這個類只做三件事:發 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/

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved