1

I am writing an Android app. I have an activity in my main project which inherits from an activity in my library project. I have a custom titlebar in the base activity which has a button, which uses the following style:

<style name="TitleButton">
    <item name="android:padding">6dp</item>
    <item name="android:layout_width">48dip</item>
    <item name="android:layout_height">48dip</item>
    <item name="android:layout_gravity">right</item>
</style>

Works fine. In my child activity, I want to add a button. I can add the button, and it clicks and works fine, but it LOOKS wrong. I am adding the button as so:

ImageView imgAdd = new ImageView(this, null, R.style.TitleButton);
imgAdd.setImageResource(R.drawable.add);
imgAdd.setClickable(true);
imgAdd.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        addGroup();
    }           
});

FrameLayout tb = (FrameLayout) this.findViewById(R.id.Header);

FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
    tb.findViewById(R.id.TitleClose).getLayoutParams()
);
lp.gravity = Gravity.RIGHT;
lp.width = 48;
lp.height = 48;
lp.setMargins(0, 9, 68, 0);
imgAdd.setLayoutParams(lp);

tb.addView(imgAdd, 1);

enter image description here

Notice how the Add button which I've added through code is too big, and offset too much. I'm figuring it must be due to what was pointed out in the comments on this answer, that setting the width and height so sets them in pixels, where as the XML layout sets them in dip. So, my question is, when setting layout params in code, how can you set the unit, so that I may set my new add button to be measured in dip instead of in pixels so that it will display right?

Community
  • 1
  • 1
eidylon
  • 7,068
  • 20
  • 75
  • 118

1 Answers1

2

You can use DisplayMetrics to get current density and use it to set width, height and margins accordingly (reference here: px = dp * (dpi / 160))

Vladimir
  • 9,683
  • 6
  • 36
  • 57
  • BAH! Humbug! Conceptually, what you said makes sense, ... only problem is my tablet (where it looks wrong) is reporting that it is the same density as my phone (where it looks right). As a result, the density formula is returning a factor of 1:1, and so not changing the size at all. Thanks for the idea anyway though. – eidylon Jan 25 '12 at 06:07