解决android - How to set layout unit for parameters set in code?
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
|
相关阅读排行
- 1Android Https相关完全解析 当OkHttp遇到Https
- 2Android APK反编译详解(附图)
- 3[置顶] Android APK反编译就这么简单 详解(附图)
- 4Android Fragment 真正的完全解析(上)
- 5Android RecyclerView 使用完全解析 体验艺术般的控件