3

I want to add an ImageView on LinearLayout with specific LayoutParams.

When I use an ImageView which is defined in dot_layout.xml, the layoutParams works fine (Commented line). However, when I dynamically created and add ImageView with layout parameters (in for loop), leftMargin doesn't work.

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

}

Here's my 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>

I was expecting a view with dot images like : * * * *

but I'm getting : **** (which has no left margin)

What am I doing wrong here? Can anyone help me?

Nari Kim Shin
  • 2,459
  • 1
  • 25
  • 33

1 Answers1

2

try this

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

and to add an ImageButton

 ImageButton myButton = new ImageButton(this);
 myButton.setBackgroundDrawable(demoCoverImage);
 LayoutParams lp = new LayoutParams(70, 60);
 ll.addView(myButton, lp);
wael
  • 444
  • 4
  • 11