RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
indicatorLayout.setLayoutParams(params);
期望指示器底部水平居中,實際未生效。
onCreate 中調用,此時 View 尚未測量佈局,WRAP_CONTENT 尺寸為 0,居中計算失效。應在 onWindowFocusChanged 或 ViewTreeObserver.OnGlobalLayoutListener 中設置。addRule 只對 RelativeLayout 子 View 生效,請確認 indicatorLayout.getParent() instanceof RelativeLayout。requestLayout() 或 XML 中同 ID View 覆蓋了代碼設置的參數。@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) indicatorLayout.getLayoutParams();
if (params == null) {
params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
}
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
indicatorLayout.setLayoutParams(params);
}
}
<RelativeLayout ...>
<View
android:id="@+id/indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
靜態佈局優先用 XML,動態調整才用代碼。
完整示例:LinuxIDC Android RelativeLayout 詳解
動態設置 LayoutParams 必須在 View 完成佈局後執行,且父容器必須是對應類型。優先使用 XML 靜態聲明,減少運行時錯誤。