Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top