コンテキストなしで dp を px に変換する非常に巧妙な方法があり、次のようになります。
public static int dpToPx(int dp) {
float density = Resources.getSystem().getDisplayMetrics().density;
return Math.round((float) dp * density);
}
Google GitHub ページのすべての Google の例では、次のアプローチを使用しています。
public static int convertDpToPixel(Context ctx, int dp) {
float density = ctx.getResources().getDisplayMetrics().density;
return Math.round((float) dp * density);
}
では、最初のアプローチに何か問題がありますか? 私にとっては、すべてのアプリで問題なく動作しますが、失敗する可能性がある場合があることを知りたいですか?