动态添加视图和LayoutParams

3
我想在具有特定LayoutParams的LinearLayout上添加一个ImageView。
当我使用在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>

我原本期望看到像这样的点图像:* * * *,但我看到的是没有左边距的****。我错在哪里了?有人能帮我吗?

你确定之前设置了 mLengthOfSlidermDensity 吗?看起来其中一个的值为0。 - Alex Salauyou
哦,是的,我把它们设置在另一个函数中了,而且值不为零。 - Nari Kim Shin
我不确定HierarchyViewer是否显示布局参数,但你可以试一下。 - pskink
1个回答

2

试试这个

 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);

谢谢你的回答,但这基本上是和我的代码一样的。问题没有得到解决。 - Nari Kim Shin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接