Android 如何使用dp移动按钮?
我试图通过脚本移动按钮。下面是它的外观:Android 如何使用dp移动按钮?,android,button,Android,Button,我试图通过脚本移动按钮。下面是它的外观: Handler handler2 = new Handler(); handler.postDelayed(new Runnable() { public void run() { float y = chatButtonOne.getY(); float yB = 40; float pxs = yB * getResources().getDispl
Handler handler2 = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
float y = chatButtonOne.getY();
float yB = 40;
float pxs = yB * getResources().getDisplayMetrics().density;
chatButtonOne.setY(y - pxs);
chatButtonOne2.setVisibility(View.VISIBLE);
}
}, 2000);
现在这个y-40在不同的设备尺寸方面是有问题的,所以我试着用dp来代替。有人知道怎么做吗
编辑:这一个成功了,我更新了我发布的原始脚本:
你需要计算像素到dp。您可以通过以下方式实现:
public static int pixelToDps(Context context, int desiredDps) {
final float scale = context.getResources().getDisplayMetrics().density; //get device density
int calculatedPixels = (int) (desiredDps * scale + 0.5f); //The +0.5 rounds up to the nearest whole number if necessary. When converted to integer, everything after the decimal is simply cut off. The +0.5 ensures that the most "correct" integer is returned
return calculatedPixels;
}
另请参见此处:您可以使用TypedValueapplyDimension将dp转换为像素:
我想这就是你要找的,就是那个。谢谢。
int pixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
getResources().getDisplayMetrics());