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>
,我期待着與斑點圖像就像一個觀點:* * * *
,但我發現:****
(沒有左旁)
我在這裏做錯了什麼?誰能幫我?
你確定你設置'mLengthOfSlider'和'mDensity'先前補充的嗎?看起來像其中一個是0. –
噢,我把這兩個函數設置爲另一個函數,並且值不爲零。 –
我不知道如果hierarchyviewer顯示佈局參數,但你可以試試 – pskink