2013-04-09 66 views
0

我想在運行時通過代碼更改按鈕的高度和寬度。通過代碼更改android按鈕的高度

我的佈局XML

<Button 
    android:id="@+id/button1" 
    android:layout_width="100dp" 
    android:layout_height="100dp" 
    android:layout_alignParentRight="true" 
    android:layout_below="@+id/button2" 
    android:background="@drawable/button1_background" 
    /> 

主要業務代碼

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    //some other code 
    int displaywidth= getResources().getDisplayMetrics().widthPixels; 
    Button f_button = (Button) findViewById(R.id.button1); 
    Log.d("F_button width before is",""+ f_button.getWidth()); 
    f_button.setWidth(displaywidth/2); 
    Log.d("F_button width after is",""+ f_button.getWidth()); 
//some other code 
} 

的logcat的同時顯示F_button後和寬度爲 「0」 之前。

我做錯了什麼。

謝謝!

+2

做的答案從http://stackoverflow.com/questions/5472445/how-to-change-size-of-button-dynamic-in-android幫助? – halex 2013-04-09 09:00:04

回答

0

在Java中使用(活動)下面的代碼

f_button.setLayoutParams (new LayoutParams(50, LayoutParams.WRAP_CONTENT)); 
0

你應該使用

int displaywidth= getResources().getDisplayMetrics().widthPixels;  
ViewGroup.LayoutParams buttonlp= (ViewGroup.LayoutParams)f_button.getLayoutParams(); 
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(displaywidth, buttonlp.height); 
buttonlp.setLayoutParams(params); 

相反的LinearLayout你應該使用該按鈕的父佈局,如果它不是LinearLayout

1

我認爲這可能對你有幫助..

Button btn = (Button)findViewById(R.id.btn1); 

android.widget.LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,60); // 60 is height you can set it as u need 

btn.setLayoutParams(lp);