簡體   English   中英

如何在所有設備上看起來相同的邊距處放置視圖?

[英]How to position the view with margin that will look same for all devices?

我正在嘗試以編程方式添加130(頂部),以將視圖放置在中央,以使其看起來不錯,但是,我不確定如何使其他Android設備(例如平板電腦)看起來一樣嗎? 在普通Android手機上將130添加到頁邊距頂部看起來不錯,但在平板電腦上看起來會有所不同。 我將如何制定邏輯以提供可以在所有設備上提供相同外觀的頁邊空白? 一些例子或技巧會很棒! 我希望收到您的來信!

margin_top = 130 // How to make this look good on all devices? 

ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(0, margin_top, 0, 0);
v.requestLayout();

我的處理方法如下:

1)。 獲取設備高度。 同時檢查答案。

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;

2)。 計算比率。

我假設您已將最高邊距設置為130dp 使用pixplicity我設法將其轉換為px

dp到px

您的手機的分辨率高度x像素權重。 讓我們將height定義為phoneHeight

在這里我也變得有些棘手。 如您所見,130dp對於ldpi,mdpi等具有不同的像素值。我個人不知道應該使用哪一種,您可以嘗試使用mdpi。 (我將嘗試進行更多研究並返回答案)。

LE:

您可以使用此方法根據手機將dp轉換為像素。 (請參閱答案)。

public static float convertDpToPixel(float dp, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    return px;
}

將返回的px用於以下公式。 (讓我們調用返回的px- convertedPx

3)。 最高保證金價值的公式。

如果我們從表中將130dp的值用於mdpi,則會得到130px。 因此公式為:

margin_top = (convertedPx / phoneHeight) * height

phoneHeight手機的高度,你目前正在測試並height使用該設備的高度displayMetrics

注意: convertedPx將是一個常量。 您只需在手機上運行此方法( convertDpToPixel )即可找出130dp的像素平均值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM