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

用 setLayoutParams 在代碼中動態調整布局:Margin 與居中

編輯:關於 Android 程式設計

布局文件寫死了的屬性,並不一定永遠合適。當需要根據運行時狀態(屏幕尺寸、數據內容、用戶操作)動態調整控件的外邊距或對齊方式時,就要靠 setLayoutParams()。本文通過一個完整示例演示如何在 Java 代碼中設置 Margin 和居中。

一、Activity 代碼

package cn.testfixmargin;

import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.app.Activity;

/**
 * Demo 描述:在代碼中設置布局的屬性,比如 Margin 和居中
 */
public class MainActivity extends Activity {

    private TextView mTextView;
    private Button mButton;

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

    private void init() {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        float density = displayMetrics.density;
        float fontScale = displayMetrics.scaledDensity;
        System.out.println("density=" + density + ",fontScale=" + fontScale);

        mTextView = (TextView) findViewById(R.id.textView);
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(new OnClickListenerImpl());
    }

    private class OnClickListenerImpl implements OnClickListener {
        @Override
        public void onClick(View v) {

            // ========== 測試 1:在代碼中為控件設置 Margin ==========
            // 注意:
            // 1. 此處 new RelativeLayout.LayoutParams(int w, int h) 的參數 w、h
            //    指的是該控件「在布局文件中所設置的」寬和高。
            // 2. 此處必須使用 RelativeLayout.LayoutParams.FILL_PARENT,
            //    因為其父容器為 RelativeLayout,所以要使用父類的布局參數。
            //
            // 官方文檔的描述是:
            //   Set the layout parameters associated with this view.
            //   These supply parameters to the parent of this view specifying
            //   how it should be arranged.
            // 也就是說 setLayoutParams() 是「給父控件看的」。
            // 這其實很好理解:只有父容器才能改變子 View 的位置布局,
            // 子 View 無法完全按照自己的意願擺放而不受父容器約束。
            //
            // RelativeLayout.LayoutParams layoutParams
            //         = new RelativeLayout.LayoutParams(
            //                 RelativeLayout.LayoutParams.FILL_PARENT,
            //                 RelativeLayout.LayoutParams.FILL_PARENT);
            // layoutParams.setMargins(280, 0, 0, 0);
            // mTextView.setLayoutParams(layoutParams);
            // ========== 測試 1 結束 ==========

            // ========== 測試 2:在代碼中設置控件居中 ==========
            // 注意:
            // 1. 參數 w、h 指該控件在布局文件中所設置的寬和高。
            // 2. 同測試 1,需使用父容器對應的 LayoutParams 類型。
            RelativeLayout.LayoutParams layoutParams =
                    new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.WRAP_CONTENT,
                            RelativeLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            mTextView.setLayoutParams(layoutParams);
            // ========== 測試 2 結束 ==========
        }
    }
}

二、布局文件 main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:textSize="25sp"
        android:layout_marginLeft="20dip" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click"
        android:textSize="25sp"
        android:layout_centerInParent="true" />

</RelativeLayout>

三、兩個關鍵要點

1. LayoutParams 必須匹配父容器的類型。 這是最容易出錯的地方。不同的 ViewGroup 有不同的 LayoutParams 內部類:LinearLayout.LayoutParams、RelativeLayout.LayoutParams、FrameLayout.LayoutParams……用錯類型會拋 ClassCastException。判斷依據很簡單——看這個 View 的「直接父容器」是什麼。

2. 構造函數的寬高含義。 new RelativeLayout.LayoutParams(w, h) 中的 w、h 描述的是「該控件自身的尺寸」,而不是父容器的尺寸。示例中之所以寫 FILL_PARENT,是為了讓控件填滿父容器;如果希望控件包裹內容,就該用 WRAP_CONTENT。原文注釋裡把參數說成「父控件的寬高」其實是個常見誤解,理解時要分清:LayoutParams 描述的是子 View 相對於父容器的排布方式與自身尺寸。

四、常用操作速查

除了示例中的居中,RelativeLayout.LayoutParams 還提供了豐富的定位規則,可以通過 addRule() 靈活組合:

// 設置四個方向的外邊距(像素)
layoutParams.setMargins(left, top, right, bottom);

// 水平居中
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);

// 垂直居中
layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);

// 在父容器中居中
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);

// 靠右 / 靠下
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

// 相對於另一個控件定位
layoutParams.addRule(RelativeLayout.BELOW, R.id.textView);

如果是 LinearLayout,則用 layoutParams.gravity 控制對齊,用 layoutParams.weight 控制權重分配;margin 也可以考慮使用 layout_marginStart / layout_marginEnd 以更好地支持 RTL 語言佈局。

五、實務建議

代碼動態改布局雖然靈活,但也有代價:每次 setLayoutParams 都可能觸發一次重新測量與佈局。如果在列表項或滾動容器中頻繁調用,容易造成掉幀。實踐中的折中做法是:能在 XML 中靜態表達的,優先寫在 XML 裡;只有確實依賴運行時條件的,才在代碼中調整,並盡量把調整放在事件觸發點(如示例中的點擊回調)而非每次 onResume 都執行。

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