動態設置layout高度

錯誤用法:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
your_layout.setLayoutParams(params);

如此使用將會報出android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams 或類似的錯誤。

正確的使用方法是

private Button mbtn; 
mbtn = (Button) findViewById(R.id.btn_test);
 LayoutParams lp;
 lp=mbtn.getLayoutParams(); 
lp.width=100; 
lp.height=200; 
mbtn.setLayoutParams(lp);
因爲Layout具有很多屬性,僅僅指定高度和寬度很多時候是有問題的,正確的方法是獲取該layout的layoutParams對象,對此對象進行修改後重新賦值。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章