2012-09-02 41 views
0

如何通過代碼定義視圖的屬性?通過視圖的代碼屬性定義

例如,我怎樣才能定義這個圖像按鈕這個屬性(寬度,高度,邊距等)?

<ImageButton 
    android:id="@+id/add_butt1" 
    android:layout_width="35dp" 
    android:layout_height="35dp" 
    android:layout_marginTop="50dp" 
    android:layout_centerHorizontal="true" 
    android:layout_centerVertical="true" 
    android:src="@drawable/button_state" 
/> 
+0

看到了這個問題: http://stackoverflow.com/questions/5389405/xml-attributes-and-their-corresponding-related-methods – Ali

回答

1

如果您在討論layout_屬性 - 比它可以用佈局的LayoutParams內部類定義,您想在其中添加視圖。例如,如果您將視圖添加到RelativeLayout,則可以使用此:http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html

 RelativeLayout layout = findViewById(R.id.my_layout); 
     RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT, 
        RelativeLayout.LayoutParams.WRAP_CONTENT); 
     params.leftMargin = 10; //px 
     layout.addView(new TextView(this), params); 
+0

,如果我不,我認爲使用WRAP_CONTENT,如果使用在我的看法在DP的維度? – esoni

+0

沒問題,只是傳遞像素值而不是WRAP_CONTENT。 ()。getDimensionPixelSize(R.dimen.id)或者 getResources()。getDimension(R.dimen.id) – AlexN