【发布时间】:2014-03-28 07:45:20
【问题描述】:
我想在LinearLayout 上添加一个ImageView,并带有特定的LayoutParams。
当我使用dot_layout.xml 中定义的ImageView 时,layoutParams 工作正常(注释行)。但是,当我使用布局参数(在 for 循环中)动态创建并添加 ImageView 时,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是否显示布局参数,但你可以试试
标签: android android-linearlayout layoutparams