英文:
How to convert px to dp in margins programmatically?
问题
我被困在这里,我不知道如何将px转换为MarginLayout中的dp<br>所以这是我的主要MarginLayout设置方法<br>
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof LinearLayout.MarginLayoutParams) {
LinearLayout.MarginLayoutParams p = (LinearLayout.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
这是点击监听器,其中元素更改其marginLayout
ArrowUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!Switch){
setMargins(AdditionalOperations, 0, 0, 0, 800);
Switch = true;
}
else{
setMargins(AdditionalOperations, 0, 0, 0, 715);
Switch = false;
}
}
});
我的目标是将像素转换为DP,并以DP值进行边距设置,而不是px。我真的被困在这里,无法理解这个想法。
英文:
I got stuck in this, I don't know how to convert px to dp in MarginLayout<br>
So this is my main MarginLayout set method<br>
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof LinearLayout.MarginLayoutParams) {
LinearLayout.MarginLayoutParams p = (LinearLayout.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
And this is on click listener where the element changes its marginLayout
ArrowUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!Switch){
setMargins(AdditionalOperations, 0, 0, 0, 800);
Switch = true;
}
else{
setMargins(AdditionalOperations, 0, 0, 0, 715);
Switch = false;
}
}
});
My goal is to conver pixels to Dp, and margin it in DP value, not px. I'm really stuck in this and can't get the idea
答案1
得分: 4
将您的像素值乘以设备显示密度。
final float density = context.getResources().getDisplayMetrics().density;
final int valueInDp = (int)(valueInPixels * density);
在您的情况下,如下所示:
ArrowUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final float density = view.getResources().getDisplayMetrics().density;
if(!Switch){
setMargins(AdditionalOperations, 0, 0, 0, 800 * density);
Switch = true;
}
else{
setMargins(AdditionalOperations, 0, 0, 0, 715 * density);
Switch = false;
}
}
});
提示: 由于您正在使用常量值,您可能希望将它们缓存起来,而不是每次都计算这些值。
英文:
Multiply your pixel values by the device display density.
final float density = context.getResources().getDisplayMetrics().density;
final int valueInDp = (int)(valueInPixels * density);
In your case would be as next:
ArrowUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final float density = view.getResources().getDisplayMetrics().density;
if(!Switch){
setMargins(AdditionalOperations, 0, 0, 0, 800 * density);
Switch = true;
}
else{
setMargins(AdditionalOperations, 0, 0, 0, 715 * density);
Switch = false;
}
}
});
Tip: As you are using constant values, you may want to cache them instead of computing the values all the time.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论