2014-03-27 36 views
1

我想在LinearLayout上添加一個ImageView以及特定的LayoutParams使用LayoutParams動態添加視圖

當我使用dot_layout.xml中定義的ImageView時,layoutParams工作正常(註釋行)。但是,當我動態創建並添加了帶有佈局參數的ImageView(在for循環中)時,leftMargin不起作用。

public void addDots() { 
    LinearLayout dotLayout = (LinearLayout) findViewById(R.id.dot_layout); 
    dotLayout.removeAllViewsInLayout(); 

    //ImageView dotImage = (ImageView) findViewById(R.id.slider_dot); 
    //LayoutParams layoutParams = (LayoutParams) dotImage.getLayoutParams(); 
    //layoutParams.leftMargin = 100; 
    //dotImage.setLayoutParams(layoutParams); 

    for(int i=0; i<INTERVAL; i++) { 
     ImageView dot = new ImageView(mContext); 
     dot.setImageDrawable(getResources().getDrawable(R.drawable.slider_dot)); 

     LayoutParams layoutParams = (LayoutParams) new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
     layoutParams.leftMargin = (int) ((i*mLengthOfSlider/INTERVAL)*mDensity); 

     dotLayout.addView(dot, layoutParams); 
    } 

} 

這裏是我的dot_layout.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" > 

<LinearLayout 
    android:id="@+id/dot_layout" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerVertical="true" 
    android:orientation="horizontal" /> 

<ImageView 
    android:id="@+id/slider_dot" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerVertical="true" 
    android:src="@drawable/slider_dot" 
    /> 
</RelativeLayout> 

,我期待着與斑點圖像就像一個觀點:* * * *

,但我發現:****(沒有左旁)

我在這裏做錯了什麼?誰能幫我?

+0

你確定你設置'mLengthOfSlider'和'mDensity'先前補充的嗎?看起來像其中一個是0. –

+0

噢,我把這兩個函數設置爲另一個函數,並且值不爲零。 –

+0

我不知道如果hierarchyviewer顯示佈局參數,但你可以試試 – pskink

回答

0

試試這個

LinearLayout ll = (LinearLayout)findViewById(R.id.layout); 

和一個ImageButton的

ImageButton myButton = new ImageButton(this); 
myButton.setBackgroundDrawable(demoCoverImage); 
LayoutParams lp = new LayoutParams(70, 60); 
ll.addView(myButton, lp); 
+0

感謝您的答案,但這與我的代碼基本相同。問題沒有解決。 –