為View設置左右切換動畫

来源:https://www.cnblogs.com/xing-star/archive/2019/04/26/10773046.html
-Advertisement-
Play Games

本文同步自http://javaexception.com/archives/64 問題: 近期的需求中,碰到了一個view切換動畫的需求。要實現的是點擊按鈕,從左到右滑動view,左邊的view消失,右邊的view出現。有點像文字跑馬燈的效果,不過這次滾動的是view,具體看截圖效果。 實現思路: ...


本文同步自http://javaexception.com/archives/64

問題:

近期的需求中,碰到了一個view切換動畫的需求。要實現的是點擊按鈕,從左到右滑動view,左邊的view消失,右邊的view出現。有點像文字跑馬燈的效果,不過這次滾動的是view,具體看截圖效果。

 

實現思路:

晚上在家寫了一個比較low的實現方案,參考的思路是Banner輪播的思路,用viewPager來進行view的切換。大致效果也還行,只不過覺得代碼量太多,使用比較麻煩。我就是想給兩個view加上可以切換動畫的效果,就要寫那麼多的代碼,感覺不划算。只好放棄此方案。

隨後想到了swipeView,發現這是一個挺好的點,可以從這裡入手。經過對swipeMenuLayout代碼的閱讀分析以及測試實踐。得出了以下的解決方案。

自定義SlideLayout.java

public class SlideLayout extends ViewGroup {
    private static final String TAG = "SlideLayout";
    private int mHeight;
    private View mContentView;
    private View mRightView;
    private boolean isAnimation = false;

    public SlideLayout(Context context) {
        this(context, null);
    }

    public SlideLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlideLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //Log.d(TAG, "onMeasure() called with: " + "widthMeasureSpec = [" + widthMeasureSpec + "], heightMeasureSpec = [" + heightMeasureSpec + "]");
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mHeight = 0;
        int contentWidth = 0;
        int childCount = getChildCount();

        final boolean measureMatchParentChildren = MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
        boolean isNeedMeasureChildHeight = false;

        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            if (childView.getVisibility() != GONE) {
                measureChild(childView, widthMeasureSpec, heightMeasureSpec);
                final MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
                mHeight = Math.max(mHeight, childView.getMeasuredHeight()/* + lp.topMargin + lp.bottomMargin*/);
                if (measureMatchParentChildren && lp.height == LayoutParams.MATCH_PARENT) {
                    isNeedMeasureChildHeight = true;
                }
                if (i == 0) {
                    mContentView = childView;
                    contentWidth = childView.getMeasuredWidth();
                } else {
                    mRightView = childView;
                }
            }
        }
        setMeasuredDimension(getPaddingLeft() + getPaddingRight() + contentWidth,
                mHeight + getPaddingTop() + getPaddingBottom());//寬度取第一個Item(Content)的寬度
        if (isNeedMeasureChildHeight) {//如果子View的height有MatchParent屬性的,設置子View高度
            forceUniformHeight(childCount, widthMeasureSpec);
        }
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    /**
     * 給MatchParent的子View設置高度
     *
     * @param count
     * @param widthMeasureSpec
     * @see android.widget.LinearLayout# 同名方法
     */
    private void forceUniformHeight(int count, int widthMeasureSpec) {
        // Pretend that the linear layout has an exact size. This is the measured height of
        // ourselves. The measured height should be the max height of the children, changed
        // to accommodate the heightMeasureSpec from the parent
        int uniformMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(),
                MeasureSpec.EXACTLY);//以父佈局高度構建一個Exactly的測量參數
        for (int i = 0; i < count; ++i) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
                if (lp.height == LayoutParams.MATCH_PARENT) {
                    // Temporarily force children to reuse their old measured width
                    int oldWidth = lp.width;//measureChildWithMargins 這個函數會用到寬,所以要保存一下
                    lp.width = child.getMeasuredWidth();
                    // Remeasure with new dimensions
                    measureChildWithMargins(child, widthMeasureSpec, 0, uniformMeasureSpec, 0);
                    lp.width = oldWidth;
                }
            }
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        //Log.e(TAG, "onLayout() called with: " + "changed = [" + changed + "], l = [" + l + "], t = [" + t + "], r = [" + r + "], b = [" + b + "]");
        int childCount = getChildCount();
        int left = 0 + getPaddingLeft();
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            if (childView.getVisibility() != GONE) {
                if (i == 0) {//第一個子View是內容 寬度設置為全屏
                    childView.layout(left, getPaddingTop(), left + childView.getMeasuredWidth(), getPaddingTop() + childView.getMeasuredHeight());
                    left = left + childView.getMeasuredWidth();
                } else {
                    childView.layout(left, getPaddingTop(), left + childView.getMeasuredWidth(), getPaddingTop() + childView.getMeasuredHeight());
                    left = left + childView.getMeasuredWidth();
                }
            }
        }
        //Log.d(TAG, "onLayout() called with: " + "maxScrollGap = [" + maxScrollGap + "], l = [" + l + "], t = [" + t + "], r = [" + r + "], b = [" + b + "]");
    }

    public void slideLeft(long duration) {
        if (isAnimation) {
            return;
        }
        AnimatorSet animatorSet = new AnimatorSet();
        final ObjectAnimator objectAnimator1 = ObjectAnimator.ofFloat(mContentView, "translationX", 0, -mContentView.getMeasuredWidth());
        final ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(mRightView, "translationX", 0, -mContentView.getMeasuredWidth());
        animatorSet.playTogether(objectAnimator1, objectAnimator2);
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                isAnimation = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                isAnimation = false;
            }
        });
        animatorSet.setDuration(duration);
        animatorSet.start();
    }

    public void slideRight(long duration) {
        if (isAnimation) {
            return;
        }
        AnimatorSet animatorSet = new AnimatorSet();
        final ObjectAnimator objectAnimator1 = ObjectAnimator.ofFloat(mContentView, "translationX", -mContentView.getMeasuredWidth(), 0);
        final ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(mRightView, "translationX", -mContentView.getMeasuredWidth(), 0);
        animatorSet.playTogether(objectAnimator1, objectAnimator2);
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                isAnimation = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                isAnimation = false;
            }
        });
        animatorSet.setDuration(duration);
        animatorSet.start();
    }
}

接著看看如何使用,調用方式。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_start"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="向左滑動" />

        <Button
            android:id="@+id/btn_start2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="向右滑動" />
    </LinearLayout>


    <me.star.animator.SlideLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/btn_show"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"
            android:padding="4dp"
            android:text="展示1"
            android:textSize="20sp"
            android:visibility="visible" />

        <TextView
            android:id="@+id/btn_show2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_green_light"
            android:padding="4dp"
            android:text="展示2"
            android:textSize="20sp" />

    </me.star.animator.SlideLayout>


</LinearLayout>
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnShow = findViewById(R.id.btn_show);
        btnShow2 = findViewById(R.id.btn_show2);
        btnStart = findViewById(R.id.btn_start);
        btnStart2 = findViewById(R.id.btn_start2);
        container = findViewById(R.id.container);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                container.slideLeft(3000);
            }
        });

        btnStart2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                container.slideRight(3000);
            }
        });
    }

其他相關:

看到泡網上有一個為View和Activity設置左右切換動畫的文章http://www.jcodecraeer.com/a/basictutorial/2016/1014/6672.html

代碼下載:

鏈接:https://pan.baidu.com/s/1Tg7-eJYSOZqEGU-fQY4how 密碼:c8q8

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 複製集 一、複製集概述: Mongodb複製集(replica set)由一組Mongod實例(進程)組成,包含一個Primary節點和多個Secondary節點,Mongodb Driver(客戶端)的所有數據都寫入Primary,Secondary通過oplog來同步Primary的數據,保證主 ...
  • 可以執行以下語句:select username,serial#, sid from v$session; 查詢用戶會話alter system kill session 'serial#, sid '; 刪除相關用戶會話 建議以後臺登陸刪除用戶會話1、查詢oracle的連接數select coun ...
  • [root@localhost ~]# vi /etc/exports #增加/nfs 192.168.10.132(rw,no_root_squash,no_all_squash,async) [root@testdg ~]# mount -t nfs 192.168.10.20:/nfs /rm ...
  • 有時候在我們開發的過程中並不一定記得資料庫的安裝路徑。比如要查看mysql 資料庫的安裝目錄在哪裡:我們可以通過mysql命令查看mysql的安裝路徑: 上面可以看到基礎的安裝路徑,查看資料庫data的路徑怎麼看,很簡單,把上面的參數變數緩存datadir即可: 當然上面是基於能登錄到mysql視窗 ...
  • 一、概述: AIDL是Android中IPC(Inter-Process Communication)方式中的一種,AIDL是Android Interface definition language的縮寫。 其主要作用是用於進程間額通訊。 在Android系統中,每個進程都運行在一塊獨立的記憶體中, ...
  • i500是一款強大而高效的AIoT平臺,專為攜帶型、家用或商用物聯網應用而設計,這些應用需要大量的邊緣處理、先進的多媒體功能、多台高解析度相機、相連的觸屏顯示器和多任務操作系統。 該平臺集成了Arm Cortex-A73 和 Cortex-A53 的四核集群,每個 CPU 都具備 NEON 引擎,集 ...
  • Hi3516EV300晶元特點: 處理器內核 ARM Cortex A7@ 900MHz,32KB I-Cache,32KB D-Cache /128KB L2 cache 支持 Neon 加速,集成 FPU 處理單元 視頻編碼 H.264 BP/MP/HP,支持 I/P 幀 H.265 Main ...
  • 版權聲明:本文為HaiyuKing原創文章,轉載請註明出處! 前言 這個方案只能在java中運行,無法在Android項目中運行。所以此方案是:APP將表單數據發送給後臺,後臺通過freemarker將表單數據根據模板ftl文件生成Word文件,然後返回給APP,由APP進行展現。 前期準備 1、下 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...