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

Android 交換兩個控件位置:LayoutParams 瞬間互換與 ObjectAnimator 動畫互換

編輯:關於 Android 程式設計

需求很具體:把畫面上的兩個區塊(本文用兩個 RelativeLayout)位置對調。查了幾圈,找到兩條可行路徑,各有取舍。

做法一:改動 LayoutParams 的相對關係(below 等規則),讓兩者位置互換。實現極簡,但沒有過渡動畫,是「瞬間」跳換。
做法二:用動畫平移兩個控件,得到平滑的交換效果。

待交換的結構如下,目标是让 layoutOne 與 layoutTwo 對調:

一、基於 LayoutParams 的瞬間交換

核心思路:RelativeLayout 的位置由規則決定,因此只要把兩個子 View 的 BELOW 規則互相指向對方,位置就換了。這裡有個關鍵前提——參與定位的控件必須先有 ID,因為 addRule(BELOW, id) 靠 ID 尋找錨點。示例中手動指定了幾個非 0 的 ID 供 this 使用。

public class ParamsExchangeActivity extends Activity {

    private Button btnEx;
    private LayoutInflater inflater;
    private RelativeLayout myFirst, mySecond, layoutOne, layoutTwo;

    // 手動指定 ID,注意不要使用 0
    private int btnExId     = 11;
    private int layoutOneId = 12;
    private int layoutTwoId = 13;

    // 交換旗標,用於來回切換
    private boolean TAG_firstLayoutTop = true;

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

        btnEx = (Button) findViewById(R.id.button_exchange);
        btnEx.setOnClickListener(new BtnExOnClickListener());
        inflater = getLayoutInflater();
        TAG_firstLayoutTop = true;

        // 初始化 layoutOne
        myFirst = (RelativeLayout) inflater.inflate(R.layout.layout_first, null)
                .findViewById(R.id.myFirst);
        layoutOne = (RelativeLayout) findViewById(R.id.LayoutOne);
        layoutOne.removeAllViews();
        layoutOne.addView(myFirst);

        // 初始化 layoutTwo
        mySecond = (RelativeLayout) inflater.inflate(R.layout.layout_second, null)
                .findViewById(R.id.mySecond);
        layoutTwo = (RelativeLayout) findViewById(R.id.LayoutTwo);
        layoutTwo.removeAllViews();
        layoutTwo.addView(mySecond);
    }

    public class BtnExOnClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            Toast.makeText(getBaseContext(), "exchange!", Toast.LENGTH_SHORT).show();

            btnEx.setId(btnExId);
            layoutOne.setId(layoutOneId);
            layoutTwo.setId(layoutTwoId);

            RelativeLayout.LayoutParams params;

            if (TAG_firstLayoutTop) {
                // layoutTwo 移到按鈕下方
                params = (RelativeLayout.LayoutParams) layoutTwo.getLayoutParams();
                params.removeRule(RelativeLayout.BELOW);   // 先移除舊規則
                params.addRule(RelativeLayout.BELOW, btnExId);
                layoutTwo.setLayoutParams(params);

                // layoutOne 移到 layoutTwo 下方
                params = (RelativeLayout.LayoutParams) layoutOne.getLayoutParams();
                params.removeRule(RelativeLayout.BELOW);
                params.addRule(RelativeLayout.BELOW, layoutTwoId);
                layoutOne.setLayoutParams(params);

                TAG_firstLayoutTop = false;
            } else {
                // 反向操作
                params = (RelativeLayout.LayoutParams) layoutOne.getLayoutParams();
                params.removeRule(RelativeLayout.BELOW);
                params.addRule(RelativeLayout.BELOW, btnExId);
                layoutOne.setLayoutParams(params);

                params = (RelativeLayout.LayoutParams) layoutTwo.getLayoutParams();
                params.removeRule(RelativeLayout.BELOW);
                params.addRule(RelativeLayout.BELOW, layoutOneId);
                layoutTwo.setLayoutParams(params);

                TAG_firstLayoutTop = true;
            }
        }
    }
}

兩個細節決定這段代碼能不能跑通:一是必須先 removeRule 再 addRule,否則舊規則仍生效,位置會互相牽扯;二是修改後要重新 setLayoutParams,改動才會觸發重新測量與佈局。

二、基於 ObjectAnimator 的動畫交換

核心只有兩行:

ObjectAnimator.ofFloat(layoutTwo, "translationY", -300).setDuration(1000).start();
ObjectAnimator.ofFloat(layoutOne, "translationY", 300).setDuration(1000).start();

完整實現:

public class AnimExchangeActivity extends Activity {

    private Button btnEx;
    private LayoutInflater inflater;
    private RelativeLayout myFirst, mySecond, layoutOne, layoutTwo;
    private boolean TAG_firstLayoutTop;

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

        btnEx = (Button) findViewById(R.id.button_exchange);
        btnEx.setOnClickListener(new BtnExOnClickListener());
        inflater = getLayoutInflater();
        TAG_firstLayoutTop = true;

        myFirst = (RelativeLayout) inflater.inflate(R.layout.layout_first, null)
                .findViewById(R.id.myFirst);
        layoutOne = (RelativeLayout) findViewById(R.id.LayoutOne);
        layoutOne.removeAllViews();
        layoutOne.addView(myFirst);

        mySecond = (RelativeLayout) inflater.inflate(R.layout.layout_second, null)
                .findViewById(R.id.mySecond);
        layoutTwo = (RelativeLayout) findViewById(R.id.LayoutTwo);
        layoutTwo.removeAllViews();
        layoutTwo.addView(mySecond);
    }

    public class BtnExOnClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            Toast.makeText(getBaseContext(), "exchange!", Toast.LENGTH_SHORT).show();

            if (TAG_firstLayoutTop) {
                // 上下各位移 300,完成交換
                ObjectAnimator.ofFloat(layoutTwo, "translationY", -300)
                        .setDuration(1000).start();
                ObjectAnimator.ofFloat(layoutOne, "translationY", 300)
                        .setDuration(1000).start();
                TAG_firstLayoutTop = false;
            } else {
                // 回到原位
                ObjectAnimator.ofFloat(layoutOne, "translationY", 0)
                        .setDuration(1000).start();
                ObjectAnimator.ofFloat(layoutTwo, "translationY", 0)
                        .setDuration(1000).start();
                TAG_firstLayoutTop = true;
            }
        }
    }
}

三、兩種方案的取舍

LayoutParams 方案改的是佈局規則,位置變更是真實的、持久的,旋轉螢幕或重新佈局後依然正確,但視覺上是硬切。

ObjectAnimator 方案改的是 translationY,屬於繪製層的視覺偏移,View 在佈局樹中的位置並未改變。這帶來兩個後果:好處是動畫流暢、實現極短;隱憂是動畫結束後 View 的「真實位置」與「視覺位置」不一致,若期間發生重新佈局(鍵盤彈出、鍵盤收起重排、設定 configChanges 後重建等),位移會被打回原形,畫面就會錯位。

因此實務上有個折衷做法:用動畫完成視覺過渡,在 onAnimationEnd 中同步修改 LayoutParams 並把 translationY 歸零。這樣既有平滑過渡,又能保證最終的佈局狀態是正確的。示例中寫死的 300 也建議改為動態獲取兩個控件的實際高度差,避免在不同螢幕密度或不同內容高度下出現交換後留有縫隙或重疊。

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