2013-08-16 59 views
0

我試圖創建一個可點擊的圖像按鈕W /文本,適合一個Horizo​​ntalScrollView內的列表。圖像/內容將以編程方式設置。做到這一點的最佳方式似乎是一個LinearLayout,然後包含一系列RelativeLayouts,其中包含顯示相關內容的視圖。但是,我無法在每個RelativeLayout之間獲取空間。儘管我已經在xml中設置了邊距並以編程方式設置,但它們似乎被忽略,並且RelativeLayout對象被擠壓在一起。如何在LinearLayout中的連續RelativeLayouts之間獲得空間?

一些代碼:

<RelativeLayout 
    android:id="@+id/details_image_button" 
    android:layout_width="75dp" 
    android:layout_height="100dp" 
    android:layout_marginLeft="10dp" 
    android:background="#00ff78"> 

    <ImageView 
     android:id="@+id/loadable_image_view" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     /> 

    <TextView 
     android:id="@+id/details_text_view" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textColor="#b083ef" 
     android:text="PH - Info about title" 
     android:layout_alignParentBottom="true" 
     /> 

//Code below is looped through several times 
     RelativeLayout imageButtonLayout = (RelativeLayout) inflater.inflate(R.layout.details_image_button, null); 
     RelativeLayout.LayoutParams imageButtonLayoutParams = new RelativeLayout.LayoutParams(100, 100); 
     imageButtonLayoutParams.setMargins(10, 10, 10, 10); 
     imageButtonLayout.setLayoutParams(imageButtonLayoutParams); 

,我獲取當前的結果是一個純綠色(在RelativeLayout的背景顏色),而不是一組RelativeLayouts與預期結果每個之間的空間。我怎樣才能最好地獲得每個RelativeLayout之間的餘量或緩衝區?

+0

這並不能真正「解決」你的問題,但你可以改用'padding'而不是'margin'。 – Shadesblade

+0

我幾乎可以肯定,這個問題源於沒有將父容器傳遞給你的'inflate()'調用(這會拋開邊距,因爲它不知道要使用什麼類型的LayoutParams,所以它回退到ViewGroup。的LayoutParams)。不要傳遞null,而是調用'inflate(R.layout.details_image_button,parent,false);'(或者如果您希望它立即連接,則爲true)。 – kcoppock

回答

3

如果您RelativeLayoutLinearLayout裏面,你需要使用LayoutParamsLinearLayout.LayoutParams

RelativeLayout imageButtonLayout = (RelativeLayout) 
            inflater.inflate(R.layout.details_image_button, null); 
    LinearLayout.LayoutParams imageButtonLayoutParams = new 
            LinearLayout.LayoutParams(100, 100); 
    imageButtonLayoutParams.setMargins(10, 10, 10, 10); 
    imageButtonLayout.setLayoutParams(imageButtonLayoutParams); 

的LayoutParams來自父母,而不是孩子。

相關問題