2011-03-18 122 views
1

我有一個自定義組件,我知道寬度和高度總是如下:設置自定義組件高度/寬度編程方式

android:layout_width="fill_parent" 

android:layout_height="wrap_content" 

我想避免必須指定XML的寬度和高度,因爲任何其他設置是錯誤的。

我試過很多東西,但沒有任何效果。例如,該代碼不起作用:

public class MyLayout extends ViewGroup {... 

LayoutParams layoutParams = 
new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); 
setLayoutParams(layoutParams); 

但無論我做什麼,我得到的異常消息「您必須提供layout_width屬性。」如果我放回XML layout_widthlayout_height就會消失。

我也試過重寫onFinishInflate(),但是永遠不會被調用。我嘗試從ViewViewGroupTableLayout繼承。我試過呼叫getLayoutParams(),但它返回null。

如何讓我的自定義組件不需要這些在XML中指定的組件?

請不要嗤之以鼻。

謝謝。

+0

試試這個http://androidactivity.wordpress.com/2011/10/04/use-dip-sp-metrics-programmatically/而不是setWidth嘗試setMinWidth希望它有幫助 – 2011-10-04 15:11:41

回答

1

您有答案,

的LayoutParams的LayoutParams =新的LayoutParams(寬度,高度); setLayoutParams(layoutParams);

高度和寬度以像素,DIP,SP指定

另外,他們中的一些提供自動調用setHeight和setWidth方法,你可以使用它們。

+0

正如我所說,這是行不通的。它執行,但在施工後仍會拋出相同的異常。謝謝您的好意。 – user405821 2011-03-18 05:59:17

+1

高度和寬度提供在哪一個? px,dip或sp?它不能一次全部都是,對吧?假設我做了新的LayoutParams(10,10),它是10傾角? 10 px? 10 sp? – 2012-04-15 03:55:22

相關問題