Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add view with LayoutParams

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?

like image 957
Nari Kim Shin Avatar asked Apr 17 '26 10:04

Nari Kim Shin


1 Answers

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);
like image 175
wael Avatar answered Apr 21 '26 02:04

wael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!