我有一個自定義組件,我知道寬度和高度總是如下:設置自定義組件高度/寬度編程方式
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_width
,layout_height
就會消失。
我也試過重寫onFinishInflate()
,但是永遠不會被調用。我嘗試從View
,ViewGroup
和TableLayout
繼承。我試過呼叫getLayoutParams()
,但它返回null。
如何讓我的自定義組件不需要這些在XML中指定的組件?
請不要嗤之以鼻。
謝謝。
試試這個http://androidactivity.wordpress.com/2011/10/04/use-dip-sp-metrics-programmatically/而不是setWidth嘗試setMinWidth希望它有幫助 – 2011-10-04 15:11:41