TrueCH
TrueCH

Reputation: 501

setLayoutParams does not display things correctly

When I'm setting my layout parameters with xml, it works fine. But when I'm trying to set layout parameters programmatically, it works wrong. where did I failed?

I need to set parameters in my LinearLayout, here it is:

<LinearLayout
        android:id="@+id/buttons_layout"
        android:layout_width="231dp"
        android:layout_height="40dp"
        android:layout_marginTop="40dp"
        android:layout_marginRight="85dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:orientation="horizontal"
        android:baselineAligned="true"
        android:weightSum="603" >

And here is my code to set params:

rl = (LinearLayout)findViewById(R.id.buttons_layout);
lp = new RelativeLayout.LayoutParams(pixelsFromDP(231), pixelsFromDP(40));
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp.setMargins(0, pixelsFromDP(40), pixelsFromDP(85), 0);
rl.setLayoutParams(lp);

Here is what I'm getting by setting parameters by xml: enter image description here

And here is what I'm getting by setting parameters programmatically: enter image description here

method pixelsFromDP returns int value:

public int pixelsFromDP(int pixels){
        return (int)(40 * getResources().getDisplayMetrics().density + 0.5f);
    }

The reason of using this method is that in LayoutParams values are in pixels, but i need values in dp, so in this methos I'm converting dp into pixels depends on screen density

Oh shi, I found a mistake! OMG I'm so stupid :D

Probled solved by replacing "40" by "pixels" in method pixelsFromDP

Upvotes: 2

Views: 3025

Answers (2)

Pawan Yadav
Pawan Yadav

Reputation: 1782

// Try this It work fine for me. I thinks there is some problem in pixelsFromDP()

    LinearLayout  rl = (LinearLayout)findViewById(R.id.buttons_layout);
    LayoutParams    lp = new RelativeLayout.LayoutParams(231, 40);
      lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
      lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
      lp.setMargins(0, 40, 85, 0);
      rl.setBackgroundColor(Color.DKGRAY);
      rl.setLayoutParams(lp);

Upvotes: 0

ibecar
ibecar

Reputation: 415

I think LayoutParams are used in measuring phase, so when you do this programatically, you have to re-measure the layout, i would try to use invalidate(). I'm not 100% sure about this, but i think it's worth a shot.

Normally i would add this just as a comment, but as I don't have enough rep i have to post this as answer.

Upvotes: 1

Related Questions