Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

高仿網易新聞頂部滑動標籤列的實作

編輯:Android 開發實例

這是網易新聞的主頁。底部用 TabHost 就能做出來,很基本;真正好看的是頂部那條會滑動的標籤列——點擊任一標籤,游標方塊會平滑滑到對應位置,同時切換下方內容。第一次模仿這種效果,有些地方還不夠細緻,但基本行為已經完整。

實作思路

不使用 TabHost 或 ViewPager,而是用最原始的方式手工打造,核心只有三個步驟:

1、版面上一條 LinearLayout 平均分成四格,每格放一個 TextView 當標籤;
2、另外準備一個「游標」TextView,背景是一張標籤底圖,用 RelativeLayout 的 layout 參數把它疊到目前選中的位置;
3、切換時計算目標位置與目前位置的 X 座標差,用 TranslateAnimation 讓游標滑過去,同時換掉下方的內容區。

版面檔(main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:background="#ffffff"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <!-- 頂部標籤列 -->
    <LinearLayout
        android:id="@+id/layoutBar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/big_button_up"
        android:orientation="horizontal">

        <RelativeLayout
            android:id="@+id/layout1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1.0">
            <TextView
                android:id="@+id/tab1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="新聞" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/layout2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1.0">
            <TextView
                android:id="@+id/tab2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="體育" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/layout3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1.0">
            <TextView
                android:id="@+id/tab3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="娛樂" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/layout4"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1.0">
            <TextView
                android:id="@+id/tab4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="更多" />
        </RelativeLayout>
    </LinearLayout>

    <!-- 內容區 -->
    <LinearLayout
        android:id="@+id/page"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/layoutBar"
        android:background="#ffffff"
        android:orientation="vertical" >
    </LinearLayout>
</RelativeLayout>

核心程式碼

程式碼已重新整理過縮排與空白,並補上必要的 import,方便閱讀:

package cn.com.karl.slider;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class SliderBarActivity extends Activity {

    private RelativeLayout layout;
    private RelativeLayout layout1, layout2, layout3, layout4;

    private TextView tab1, tab2, tab3, tab4;
    private TextView first;

    private int current = 1;

    private LinearLayout page;

    private boolean isAdd = false;
    private int select_width;
    private int select_height;
    private int firstLeft;
    private int startLeft;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }

    private void init() {
        layout = (RelativeLayout) findViewById(R.id.root);

        layout1 = (RelativeLayout) findViewById(R.id.layout1);
        layout2 = (RelativeLayout) findViewById(R.id.layout2);
        layout3 = (RelativeLayout) findViewById(R.id.layout3);
        layout4 = (RelativeLayout) findViewById(R.id.layout4);

        page = (LinearLayout) this.findViewById(R.id.page);

        tab1 = (TextView) findViewById(R.id.tab1);
        tab1.setOnClickListener(onClickListener);
        tab2 = (TextView) findViewById(R.id.tab2);
        tab2.setOnClickListener(onClickListener);
        tab3 = (TextView) findViewById(R.id.tab3);
        tab3.setOnClickListener(onClickListener);
        tab4 = (TextView) findViewById(R.id.tab4);
        tab4.setOnClickListener(onClickListener);

        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        rl.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);

        // 建立游標(滑動方塊)
        first = new TextView(this);
        first.setTag("first");
        first.setGravity(Gravity.CENTER);
        first.setBackgroundResource(R.drawable.slidebar);
        first.setText(tab1.getText());

        page.addView(LayoutInflater.from(getApplicationContext())
                .inflate(R.layout.page1, null));

        // 初始放在第 1 格
        switch (current) {
            case 1:
                layout1.addView(first, rl);
                current = R.id.tab1;
                break;
            case 2:
                layout2.addView(first, rl);
                current = R.id.tab2;
                break;
            case 3:
                layout3.addView(first, rl);
                current = R.id.tab3;
                break;
            case 4:
                layout4.addView(first, rl);
                current = R.id.tab4;
                break;
            default:
                break;
        }
    }

    /** 第一次點擊時,把游標從原格子搬到 root 上,之後才好自由移動 */
    private void replace() {
        switch (current) {
            case R.id.tab1:
                changeTop(layout1);
                break;
            case R.id.tab2:
                changeTop(layout2);
                break;
            case R.id.tab3:
                changeTop(layout3);
                break;
            case R.id.tab4:
                changeTop(layout4);
                break;
            default:
                break;
        }
    }

    private void changeTop(RelativeLayout relativeLayout) {
        TextView old = (TextView) relativeLayout.findViewWithTag("first");

        select_width = old.getWidth();
        select_height = old.getHeight();

        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(
                select_width, select_height);
        rl.leftMargin = old.getLeft() + ((RelativeLayout) old.getParent()).getLeft();
        rl.topMargin = old.getTop() + ((RelativeLayout) old.getParent()).getTop();

        firstLeft = old.getLeft() + ((RelativeLayout) old.getParent()).getLeft();

        // 在 root 上另建一個可移動的游標
        TextView tv = new TextView(this);
        tv.setTag("move");
        tv.setBackgroundResource(R.drawable.slidebar);

        layout.addView(tv, rl);
        relativeLayout.removeView(old);
    }

    private OnClickListener onClickListener = new OnClickListener() {
        public void onClick(View v) {
            if (!isAdd) {
                replace();
                isAdd = true;
            }

            TextView topSelect = (TextView) layout.findViewWithTag("move");
            topSelect.setGravity(Gravity.CENTER);
            topSelect.setText(tab1.getText());

            int tabLeft;
            int endLeft = 0;
            boolean run = false;

            switch (v.getId()) {
                case R.id.tab1:
                    if (current != R.id.tab1) {
                        page.removeAllViews();
                        tabLeft = ((RelativeLayout) tab1.getParent()).getLeft()
                                + tab1.getLeft() + tab1.getWidth() / 2;
                        endLeft = tabLeft - select_width / 2;
                        current = R.id.tab1;
                        topSelect.setText(tab1.getText());
                        run = true;
                        page.addView(LayoutInflater.from(getApplicationContext())
                                .inflate(R.layout.page1, null));
                    }
                    break;

                case R.id.tab2:
                    if (current != R.id.tab2) {
                        page.removeAllViews();
                        tabLeft = ((RelativeLayout) tab2.getParent()).getLeft()
                                + tab2.getLeft() + tab2.getWidth() / 2;
                        endLeft = tabLeft - select_width / 2;
                        current = R.id.tab2;
                        topSelect.setText(tab2.getText());
                        run = true;
                        page.addView(LayoutInflater.from(getApplicationContext())
                                .inflate(R.layout.page2, null));
                    }
                    break;

                case R.id.tab3:
                    if (current != R.id.tab3) {
                        page.removeAllViews();
                        tabLeft = ((RelativeLayout) tab3.getParent()).getLeft()
                                + tab3.getLeft() + tab3.getWidth() / 2;
                        endLeft = tabLeft - select_width / 2;
                        current = R.id.tab3;
                        topSelect.setText(tab3.getText());
                        run = true;
                        page.addView(LayoutInflater.from(getApplicationContext())
                                .inflate(R.layout.page3, null));
                    }
                    break;

                case R.id.tab4:
                    if (current != R.id.tab4) {
                        page.removeAllViews();
                        // 注意:原本這裡誤用了 tab3 的位置,已修正為 tab4
                        tabLeft = ((RelativeLayout) tab4.getParent()).getLeft()
                                + tab4.getLeft() + tab4.getWidth() / 2;
                        endLeft = tabLeft - select_width / 2;
                        current = R.id.tab4;
                        topSelect.setText(tab4.getText());
                        run = true;
                        page.addView(LayoutInflater.from(getApplicationContext())
                                .inflate(R.layout.page4, null));
                    }
                    break;

                default:
                    break;
            }

            if (run) {
                // 從上次的位置滑到新位置
                TranslateAnimation animation = new TranslateAnimation(
                        startLeft, endLeft - firstLeft, 0, 0);
                startLeft = endLeft - firstLeft;
                animation.setDuration(100);
                animation.setFillAfter(true);

                topSelect.bringToFront();
                topSelect.startAnimation(animation);
            }
        }
    };
}

動畫的關鍵細節

整個效果成立的前提有兩個:

一是 bringToFront()。游標在 root 上必須蓋在標籤文字之上,或者至少不互相遮擋,呼叫它可確保層序正確。

二是 setFillAfter(true)。TranslateAnimation 預設在動畫結束後會把 View 拉回原始位置,加上這個設定才會停留在終點。若沒有它,游標會「滑過去又跳回來」。

另外,startLeft 記的是「上一次的位移量」,每次點擊時把新的 endLeft - firstLeft 減掉起始基準,就能算出這次要移動的距離,形成連續滑動的效果。

程式碼中修正與可優化之處

原始版本有幾個問題值得說明:

1、tab4 的位置計算誤用 tab3。原程式碼中 case R.id.tab4 分支寫的是 tab3.getLeft(),會導致游標滑到錯誤的位置,上面已修正。

2、四個 case 幾乎完全相同。可以抽成一個方法,傳入「目標 tab、對應的 page 版面資源 id」兩個參數,程式碼量能砍掉三分之二,新增標籤時也不必再複製一段。

3、硬寫的座標計算很脆弱。靠 getLeft() 累加父容器位置來推算座標,在螢幕尺寸或字型大小變動時容易偏移。更穩健的做法是改用 view.getLocationOnScreen() 或直接把游標實作成 TabLayout 的 indicator。

4、內容切換用 removeAllViews + inflate。每次切換都重新解析一次 XML,開銷不小。改以 ViewPager2 搭配 FragmentStateAdapter,可以獲得滑動切頁、頁面預載與狀態保存,程式碼反而更少。

效果預覽

由於時間倉促,這份程式碼沒有逐行註解,實際效果請自行編譯體驗並持續改進。

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