2011年7月24日星期日

通過 Java 代碼設定 layout_width 為 50%

參考前文"怎麼設定layout_width為50%", 我們可以設置 <Button> 的重量參數(weight)設定 layout_width 為 50%.

但當我們使用 Java 代碼, 如果定義按鈕的 LayoutParams 為 LayoutParams, 我們是不能設置重量參數(weight)的!

可以把按鈕的 LayoutParams 定義為 LinearLayout.LayoutParams, 便可以通過 new LinearLayout.LayoutParams() 或 LinearLayout.LayoutParams.weight 設置重量參數(weight).

通過 Java 代碼設定 layout_width 為 50%

package com.AndroidWeight;

import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class AndroidWeightActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setOrientation(LinearLayout.HORIZONTAL);

// Half Button 1
LinearLayout subLayout1 = new LinearLayout(getApplicationContext());
LinearLayout.LayoutParams paramsSubLayout1
= new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1.0f);
subLayout1.setLayoutParams(paramsSubLayout1);
subLayout1.setOrientation(LinearLayout.VERTICAL);

Button buttonHalfWidth1 = new Button(getApplicationContext());
buttonHalfWidth1.setText("Half Width 1");
LayoutParams paramsHalfWidth1
= new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
buttonHalfWidth1.setLayoutParams(paramsHalfWidth1);

// Half Button 2
Button buttonHalfWidth2 = new Button(getApplicationContext());
buttonHalfWidth2.setText("Half Width 2");
LinearLayout.LayoutParams paramsHalfWidth2
= new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
paramsHalfWidth2.weight = 1.0f;
buttonHalfWidth2.setLayoutParams(paramsHalfWidth2);

//--------
subLayout1.addView(buttonHalfWidth1);
layout.addView(subLayout1);
layout.addView(buttonHalfWidth2);

setContentView(layout);
}
}

沒有留言:

發佈留言