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

Android TV 開發實戰:從環境配置到焦點導航的問題排查

編輯:關於 Android 程式設計

前言

本文記錄了幾個 TV 應用開發中常見問題的解決方案。如果你對 TV 開發不感興趣,大可以直接跳過。

最近接到一個需求,要出一個 TV 版本的 App。由於此前並未深入了解 TV 版與手機版到底有何差別,於是做了一番研究並寫了些 Demo,過程中確實踩了不少坑。一開始遇到問題時只是淺嘗輒止地試了試,發現很多都找不到現成答案,上網搜索也收穫寥寥——大概是做 TV 的人相對較少,網上多是照著 Google 官方樣例照搬一遍而已。於是便仔細研究了這些問題,把解法整理出來,希望能讓後來者少走彎路。若你有更好的方案,也歡迎一起探討分享。

Demo 展示

這裡做了一個 Demo,以下截圖均為最終運行後的效果。由於是在模擬器上截圖,導致部分控件加載不完全,但在真實的機頂盒上並無問題:

開發過程

雖然 Google 官方聲稱手機 App 稍作改動就能運行在 TV 上,但兩者終究存在差異,仍需針對 TV 版做部分設置。

首先是配置文件的改動,需要在 AndroidManifest 中配置以下屬性:

<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
<uses-feature android:name="android.software.leanback" android:required="true" />

同時還需要配置一個 action 為 android.intent.action.MAIN、category 為 android.intent.category.LEANBACK_LAUNCHER 的 Activity:

<intent-filter>
    <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>

如果記不住這些配置也沒關係——直接新建一個 TV 工程即可,預設創建的 TV 工程就已包含上述配置,而且它本身就等同於一個可直接運行的 Demo,內含大量 TV 開發控件,是很好的學習資料。值得一提的是,Android SDK 中 samples 裡的 TV 樣例程序直接導入往往跑不起來,需要修改不少東西,但其實質內容與新建工程別無二致,因此不必執著於導入樣例。

根據前面的效果圖,主界面配置頁面的布局如下:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:background="@drawable/global_bg"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:paddingLeft="42dp"
    android:paddingRight="42dp">
    <RelativeLayout
        android:clickable="true"
        android:layout_height="@dimen/gap_86_dp"
        android:layout_width="match_parent">
        <TextView
            android:drawableLeft="@drawable/tv_logo"
            android:drawablePadding="@dimen/gap_8_dp"
            android:gravity="center"
            android:layout_centerVertical="true"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="@string/itv_name"
            android:textColor="@color/white"
            android:textSize="@dimen/text_size_20" />
        <TextView
            android:background="@drawable/navigation_tab_bar_selector"
            android:focusable="true"
            android:gravity="center"
            android:id="@+id/settings_tab"
            android:layout_alignParentRight="true"
            android:layout_height="match_parent"
            android:layout_marginRight="@dimen/gap_45_dp"
            android:layout_width="wrap_content"
            android:text="@string/setting"
            android:textColor="@color/navigation_text_selector"
            android:textSize="@dimen/text_size_20" />
        <TextView
            android:background="@drawable/navigation_tab_bar_selector"
            android:focusable="true"
            android:gravity="center"
            android:id="@+id/contact_tab"
            android:layout_height="match_parent"
            android:layout_marginRight="@dimen/gap_45_dp"
            android:layout_toLeftOf="@id/settings_tab"
            android:layout_width="wrap_content"
            android:text="@string/contact"
            android:textColor="@color/navigation_text_selector"
            android:textSize="@dimen/text_size_20" />
        <TextView
            android:background="@drawable/navigation_tab_bar_selector"
            android:focusable="true"
            android:gravity="center"
            android:id="@+id/dial_tab"
            android:layout_height="match_parent"
            android:layout_marginRight="@dimen/gap_65_dp"
            android:layout_toLeftOf="@id/contact_tab"
            android:layout_width="wrap_content"
            android:text="@string/dial"
            android:textColor="@color/navigation_text_selector"
            android:textSize="@dimen/text_size_20" />
    </RelativeLayout>
    <View
        android:background="@color/gray1"
        android:layout_height="1px"
        android:layout_marginBottom="@dimen/gap_50_dp"
        android:layout_width="match_parent" />
    <FrameLayout
        android:id="@+id/tab_container"
        android:layout_height="match_parent"
        android:layout_width="match_parent"></FrameLayout>
</LinearLayout>

對應的界面程式碼如下:

public class HomeActivity extends Activity implements View.OnClickListener {
    private static final String[] TAGS = {"dial", "contact", "my"};
    private FragmentManager manager;
    private int showTabIndex = -1;
    private TextView dialTab, contactTab, myTab;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        findViews();
        setViewsListener();
        init();
        selectTab(0);
    }
    private void findViews() {
        dialTab = (TextView) findViewById(R.id.dial_tab);
        contactTab = (TextView) findViewById(R.id.contact_tab);
        myTab = (TextView) findViewById(R.id.settings_tab);
    }
    private void setViewsListener() {
        dialTab.setOnClickListener(this);
        contactTab.setOnClickListener(this);
        myTab.setOnClickListener(this);
    }
    private void init() { manager = getFragmentManager(); }
    private void selectTab(int index) {
        if (index == showTabIndex) return;
        dialTab.setSelected(index == 0);
        contactTab.setSelected(index == 1);
        myTab.setSelected(index == 2);
        FragmentTransaction transaction = manager.beginTransaction();
        hideFragment(showTabIndex, transaction);
        showTabIndex = index;
        showFragment(showTabIndex, transaction);
        transaction.commit();
    }
    private void hideFragment(int tabIndex, FragmentTransaction transaction) {
        Fragment fragment = getFragmentByIndex(tabIndex);
        if (fragment != null) transaction.hide(fragment);
    }
    private Fragment getFragmentByIndex(int index) {
        if (index >= 0 && index < TAGS.length) return manager.findFragmentByTag(TAGS[index]);
        return null;
    }
    private void showFragment(int tabIndex, FragmentTransaction transaction) {
        Fragment fragment = getFragmentByIndex(tabIndex);
        if (fragment == null) {
            switch (tabIndex) {
                case 0: fragment = new DialFragment(); break;
                case 1: fragment = new VerticalGridFragment(); break;
                case 2: fragment = new MyFragment(); break;
            }
            transaction.add(R.id.tab_container, fragment, TAGS[tabIndex]);
        } else {
            transaction.show(fragment);
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dial_tab: selectTab(0); return;
            case R.id.contact_tab: selectTab(1); return;
            case R.id.settings_tab: selectTab(2); return;
        }
    }
}

該界面主要用 Fragment 實現三個子界面——撥號、好友與設置(設置頁只是個充數的空界面)。撥號界面內部又包含兩個子 Fragment:左側撥號盤占據屏幕一份,右側通訊錄占據三份,且右側復用了主界面的 VerticalGridFragment。撥號界面的布局如下:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:background="@color/transparent"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="horizontal">
    <FrameLayout
        android:id="@+id/dial_pan"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_width="0dp"></FrameLayout>
    <FrameLayout
        android:id="@+id/contact_pan"
        android:layout_height="match_parent"
        android:layout_marginLeft="@dimen/gap_12_dp"
        android:layout_weight="3"
        android:layout_width="0dp"></FrameLayout>
</LinearLayout>

由於僅用於展示,撥號盤部分的程式碼寫得較為粗放,直接堆了多個按鈕。這裡不再逐一貼出冗長的 XML,核心思路是透過 setNextFocusUpId 等方法為每個按鈕指定焦點走向。好友界面則使用自定義的 VerticalGridFragment 與 ContactPresenter 來呈現網格式列表,Presenter 仿照官方的 CardPresenter,但採用了自定義的 ContactView 控件(一個繼承自 LinearLayout、含有一個 ImageView 與兩個 TextView 的組合控件)。

整個界面程式碼至此基本完成,接下來看看實戰中遇到的各類問題。

問題排查列表

問題 1:控件不能被遙控器選中、無法導航

這往往是因為控件沒有設置 android:focusable="true"。只有像 Button、EditText 這類預設就能獲得焦點的控件才無需設置。

問題 2:控件選中後看不出效果

TV 上默認的選中態沒有視覺反饋,因此你需要為控件設置 focused 效果。以往在手機上可能只需設置 selector 的 pressed 或 selected 屬性,但針對 TV 必須設置 focused 屬性。例如撥號鍵盤選中後會出現一個圓形高亮背景框:

為此可為每個按鍵添加如下 selector:

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/key_board_hover" android:state_focused="true"></item>
    <item android:drawable="@drawable/key_board_hover" android:state_pressed="true"></item>
    <item android:drawable="@drawable/key_board_hover" android:state_checked="true"></item>
    <item android:drawable="@color/transparent"></item>
</selector>

問題 3:TV launcher 中沒有入口圖標

若要在桌面出現入口圖標,必須在 AndroidManifest 中配置 action 為 android.intent.action.MAIN、category 為 android.intent.category.LAUNCHER 的 Activity。該配置與 LEANBACK_LAUNCHER 並不衝突,可以讓入口 Activity 使用 LAUNCHER,另一個頁面使用 LEANBACK_LAUNCHER。

問題 4:TV launcher 中的圖標模糊不清

直接把手機 App 的 launcher 圖標用到 TV 上會被拉伸變糊,因為 TV 圖標尺寸往往更大。手機裡通常是 48×48、72×72、96×96,而 TV 需要更大的尺寸。雖然官方未給出建議值,這裡推薦 180×180,並在多個文件夾放置同一圖標,加載後就會清晰許多。

問題 5:遙控器導航到了非預期的控件

當界面存在多個可 focus 的控件時,系統會自動選擇與當前控件最鄰近的一個作為下一站。若想精確指定,可以呼叫 setNextFocusUpId 等方法明確下一個控件的 ID,例如 view1.setNextFocusUpId(R.id.dial_tab),前提是該 id 位於當前顯示的界面中。

問題 6:VerticalGridFragment 首次加載時第一個項占滿整個界面

這應是官方的一個 bug,非首次加載時不會出現。原因是選中後系統會在選中控件後插入兩幀 NonOverlappingView,每幀都用 .9 圖標作為背景;而首次加載時第一個選中控件的寬高被錯誤計算成 16777211 這類超出屏幕的值。解決方案有三:其一,把布局中的 match_parent 改為 wrap_content;其二,對 VerticalGridPresenter 調用 setShadowEnabled(false);其三,替換掉 .9 圖片。

問題 6(續):自定義 Presenter 導致選中高亮不居中

當 ArrayObjectAdapter 使用自定義 Presenter、且未使用系統的 ImageCardView 時,選中放大效果會向右下方偏移而非均勻覆蓋四周。目前官方 style 只針對 ImageCardView,尚未深入研究調整方式,這裡給出一個規避方案:將高亮效果設為不放大,即 new VerticalGridPresenter(FocusHighlight.ZOOM_FACTOR_NONE)。

問題 6(續):VerticalGridFragment 頂層控件無法向上導航

這一問題其實是被系統攔截了。系統的 VerticalGridFragment 加載了 lb_vertical_grid_fragment 布局,其中包含一個 BrowseFrameLayout,並為它設置了 setOnFocusSearchListener。當焦點到達最頂層再向上查找時,會走到父布局 BrowseFrameLayout 的 listener,而該 listener 在 focused != mTitleView 且方向為 FOCUS_UP 時,會強制把焦點交給 mTitleView——即便並未顯示 title 也是如此。這被認為是系統的一個 bug。解法是重寫一份自己的 lb_vertical_grid_fragment 布局來覆蓋系統布局,並把 BrowseFrameLayout 替換成自定義版本,將其 setOnFocusSearchListener 方法置空,如此便能恢復正常的向上導航。

總結

當然,可能還有各種各樣本文未涉及的問題,也欢迎大家指正上文內容,並分享你在 TV 開發中遇到的新問題。

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