LayoutParams是ViewGroup的內部類,用于設置和獲取View在父容器中的布局參數。
使用LayoutParams的步驟如下:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
params.weight = 1;
view.setLayoutParams(params);
完整的示例代碼如下:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
params.weight = 1;
view.setLayoutParams(params);
以上代碼將創建一個LinearLayout.LayoutParams對象,并設置寬度為MATCH_PARENT、高度為WRAP_CONTENT、權重為1,然后將這個LayoutParams對象設置給view。