ITKeyword,专注技术干货聚合推荐

注册 | 登录

解决android - How to set layout unit for parameters set in code?

itPublisher 分享于

2021腾讯云限时秒杀,爆款1核2G云服务器298元/3年!(领取2860元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1062

2021阿里云最低价产品入口+领取代金券(老用户3折起),
入口地址https://www.aliyun.com/minisite/goods

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

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?

android layout units-of-measurement layoutparams
|
  this question
asked Jan 24 '12 at 7:36 eidylon 3,516 15 56 99

 | 

1 Answers
1

解决方法

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


|
  this answer
answered Jan 24 '12 at 7:47 Vladimir 6,934 6 26 49      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 6:07

 | 


相关阅读排行


相关内容推荐

最新文章

×

×

请激活账号

为了能正常使用评论、编辑功能及以后陆续为用户提供的其他产品,请激活账号。

您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱

如果您没有收到激活邮件,请注意检查垃圾箱。