سؤال

لقد قمت بإنشاء بعض العناصر المخصصة ، وأريد وضعها برمجيًا على الزاوية اليمنى العليا (n وحدات البكسل من الحافة العليا و m وحدات البكسل من الحافة اليمنى). لذلك أحتاج إلى الحصول على عرض الشاشة وارتفاع الشاشة ثم ضبط الموضع:

int px = screenWidth - m;
int py = screenHeight - n;

كيف أحصل screenWidth و screenHeight في النشاط الرئيسي؟

هل كانت مفيدة؟

المحلول

إذا كنت تريد أبعاد العرض بالبكسلات ، يمكنك استخدامها getSize:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

إذا لم تكن في Activity يمكنك الحصول على الافتراضي Display عبر WINDOW_SERVICE:

WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();

إذا كنت في جزء من جزء وترغب في الحصول على هذا النشاط فقط.

قبل getSize تم تقديمه (في مستوى API 13) ، يمكنك استخدام getWidth و getHeight الطرق التي تم إهمالها الآن:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();  // deprecated
int height = display.getHeight();  // deprecated

بالنسبة لحالة الاستخدام التي تصفها ، يبدو الهامش/الحشو في التصميم أكثر ملاءمة.

طريقة أخرى هي: DisplayMetrics

بنية تصف المعلومات العامة حول الشاشة ، مثل حجمها وكثافتها وتوسيع نطاق الخط. للوصول إلى أعضاء DisplayMetrics ، قم بتهيئة كائن مثل هذا:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

يمكننا ان نستخدم widthPixels للحصول على معلومات لـ:

"العرض المطلق للعرض بالبكسل."

مثال:

Log.d("ApplicationTagName", "Display width in px is " + metrics.widthPixels);

نصائح أخرى

طريقة واحدة هي:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();
int height = display.getHeight();

تم إهماله ، ويجب أن تجرب الكود التالي بدلاً من ذلك. يمنحك أول سطرين من التعليمات البرمجية DisplayMetrics Objecs. تحتوي هذه الكائنات على الحقول مثل heightPixels, widthPixels.

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

int height = metrics.heightPixels;
int width = metrics.widthPixels;

قد لا يجيب على سؤالك ، ولكن قد يكون من المفيد معرفة ذلك (كنت أبحث عنه بنفسي عندما أتيت إلى هذا السؤال) أنه إذا كنت بحاجة إلى بُعد عرض ولكن يتم تنفيذ رمزك عندما لم يتم وضع تخطيطه بعد (على سبيل المثال في onCreate() ) يمكنك إعداد أ ViewTreeObserver.OnGlobalLayoutListener مع View.getViewTreeObserver().addOnGlobalLayoutListener() ووضع الكود ذي الصلة الذي يحتاج إلى بُعد العرض هناك. سيتم استدعاء رد اتصال المستمع متى سيتم وضع التصميم.

(إجابة 2012 ، قد تكون قديمة) إذا كنت ترغب في دعم ما قبل قرص العسل ، فستحتاج إلى توافق متخلف قبل API 13. شيء مثل:

int measuredWidth = 0;
int measuredHeight = 0;
WindowManager w = getWindowManager();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
    Point size = new Point();
    w.getDefaultDisplay().getSize(size);
    measuredWidth = size.x;
    measuredHeight = size.y;
} else {
    Display d = w.getDefaultDisplay();
    measuredWidth = d.getWidth();
    measuredHeight = d.getHeight();
}

بالطبع ، سيتم إخراج الأساليب التي تم إهمالها في النهاية من أحدث SDKs ، ولكن بينما لا نزال نعتمد على معظم مستخدمينا الذين لديهم Android 2.1 و 2.2 و 2.3 ، هذا ما تبقى لدينا.

لقد جربت جميع "الحلول" الممكنة دون جدوى ، ولاحظت أن تطبيق Elliott Hughes 'Dalvik Explorer "يعرض دائمًا البعد الصحيح على أي إصدار من جهاز/OS Android. انتهى بي الأمر بالنظر إلى مشروعه المفتوح المصدر الذي يمكن العثور عليه هنا: https://code.google.com/p/enh/

إليك كل الكود ذي الصلة:

WindowManager w = activity.getWindowManager();
Display d = w.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
d.getMetrics(metrics);
// since SDK_INT = 1;
widthPixels = metrics.widthPixels;
heightPixels = metrics.heightPixels;
try {
    // used when 17 > SDK_INT >= 14; includes window decorations (statusbar bar/menu bar)
    widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
    heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
} catch (Exception ignored) {
}
try {
    // used when SDK_INT >= 17; includes window decorations (statusbar bar/menu bar)
    Point realSize = new Point();
    Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
    widthPixels = realSize.x;
    heightPixels = realSize.y;
} catch (Exception ignored) {
}

تحرير: نسخة محسّنة قليلاً (تجنب إطلاق النار على استثناءات على إصدار OS غير المدعوم):

WindowManager w = activity.getWindowManager();
Display d = w.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
d.getMetrics(metrics);
// since SDK_INT = 1;
widthPixels = metrics.widthPixels;
heightPixels = metrics.heightPixels;
// includes window decorations (statusbar bar/menu bar)
if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
try {
    widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
    heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
} catch (Exception ignored) {
}
// includes window decorations (statusbar bar/menu bar)
if (Build.VERSION.SDK_INT >= 17)
try {
    Point realSize = new Point();
    Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
    widthPixels = realSize.x;
    heightPixels = realSize.y;
} catch (Exception ignored) {
}

أبسط طريقة:

 int screenHeight = getResources().getDisplayMetrics().heightPixels;
 int screenWidth = getResources().getDisplayMetrics().widthPixels; 

للوصول إلى ارتفاع شريط الحالة لأجهزة Android ، نفضل طريقة برمجية للحصول عليها:

عينة من الرموز

int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resId > 0) {
    result = getResources().getDimensionPixelSize(resId);
}

المتغير result يعطي الارتفاع في بكسل.

للوصول السريع

Enter image description here

لمزيد من المعلومات حول ارتفاع Title bar, Navigation bar و Content View, ، يرجى النظر إلى أحجام شاشة جهاز Android.

احصل أولاً على العرض (على سبيل المثال findViewById()) ثم يمكنك استخدام getWidth () على الرأي نفسه.

لديّ وظيفتان ، إحداهما لإرسال السياق والآخر يحصل على الارتفاع والعرض بالبكسل:

public static int getWidth(Context mContext){
    int width=0;
    WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    if(Build.VERSION.SDK_INT>12){
        Point size = new Point();
        display.getSize(size);
        width = size.x;
    }
    else{
        width = display.getWidth();  // Deprecated
    }
    return width;
}

و

public static int getHeight(Context mContext){
    int height=0;
    WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    if(Build.VERSION.SDK_INT>12){
        Point size = new Point();
        display.getSize(size);
        height = size.y;
    }
    else{
        height = display.getHeight();  // Deprecated
    }
    return height;
}

للتوسع ديناميكيًا باستخدام XML ، توجد سمة تسمى "Android: Layout_Weight"

مثال أدناه ، تم تعديله من استجابة سينك على هذا الموضوع, ، يظهر زرًا يستغرق 75 ٪ من الشاشة (الوزن = .25) وعرض نص يتناول 25 ٪ المتبقية من الشاشة (الوزن = .75).

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight=".25"
        android:text="somebutton">

    <TextView android:layout_width="fill_parent"
        android:layout_height="Wrap_content"
        android:layout_weight=".75">
</LinearLayout>

هذا هو الرمز الذي أستخدمه للمهمة:

// `activity` is an instance of Activity class.
Display display = activity.getWindowManager().getDefaultDisplay();
Point screen = new Point();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
    display.getSize(screen);
} else {            
    screen.x = display.getWidth();
    screen.y = display.getHeight();
}

يبدو نظيفًا بما فيه الكفاية ، ومع ذلك ، يعتني بالإهمال.

أليس هذا حل أفضل بكثير؟ DisplayMetrics يأتي مع كل ما تحتاجه ويعمل من API 1.

public void getScreenInfo(){
    DisplayMetrics metrics = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);

    heightPixels = metrics.heightPixels;
    widthPixels = metrics.widthPixels;
    density = metrics.density;
    densityDpi = metrics.densityDpi;
}

يمكنك أيضًا الحصول على الشاشة الفعلية (بما في ذلك ديكورات الشاشة ، مثل شريط الحالة أو شريط التنقل في البرامج) باستخدام getRealMetrics, ، لكن هذا يعمل على 17+ فقط.

هل فاتني شيء؟

مجرد إضافة إلى إجابة فرانشيسكو. المراقب الآخر الأكثر ملاءمة ، إذا كنت ترغب في معرفة الموقع الموجود في النافذة أو الموقع في الشاشةViewTreeObserver.onpredRawlistener ()

يمكن استخدام هذا أيضًا للعثور على سمات أخرى للمنظر غير المعروف في الغالب في الوقت onCreate () على سبيل المثال الموضع الذي تم تمريره ، الموضع المقوس.

ابحث عن عرض وارتفاع الشاشة:

width = getWindowManager().getDefaultDisplay().getWidth();
height = getWindowManager().getDefaultDisplay().getHeight();

باستخدام هذا ، يمكننا الحصول على أحدث وفوق SDK 13.

// New width and height
int version = android.os.Build.VERSION.SDK_INT;
Log.i("", " name == "+ version);
Display display = getWindowManager().getDefaultDisplay();
int width;
if (version >= 13) {
    Point size = new Point();
    display.getSize(size);
    width = size.x;
    Log.i("width", "if =>" +width);
}
else {
    width = display.getWidth();
    Log.i("width", "else =>" +width);
}

باستخدام الكود التالي في النشاط.

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int wwidth = metrics.widthPixels;
DisplayMetrics dimension = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dimension);
int w = dimension.widthPixels;
int h = dimension.heightPixels;

لقد وجدت أن هذا فعل الخدعة.

Rect dim = new Rect();
getWindowVisibleDisplayFrame(dim);

بحاجة إلى القول ، إذا لم تكن في Activity, ، ولكن في View (أو لديك متغير من View اكتب في نطاقك) ، لا توجد حاجة إلى الاستخدام WINDOW_SERVICE. ثم يمكنك استخدام طريقتين على الأقل.

أولاً:

DisplayMetrics dm = yourView.getContext().getResources().getDisplayMetrics();

ثانيا:

DisplayMetrics dm = new DisplayMetrics();
yourView.getDisplay().getMetrics(dm);

كل هذه الطرق التي نسميها هنا لم يتم إهمالها.

public class AndroidScreenActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        String str_ScreenSize = "The Android Screen is: "
                                   + dm.widthPixels
                                   + " x "
                                   + dm.heightPixels;

        TextView mScreenSize = (TextView) findViewById(R.id.strScreenSize);
        mScreenSize.setText(str_ScreenSize);
    }
}

للحصول على أبعاد الشاشة ، استخدم سيارات العرض

DisplayMetrics displayMetrics = new DisplayMetrics();
if (context != null) 
      WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
      Display defaultDisplay = windowManager.getDefaultDisplay();
      defaultDisplay.getRealMetrics(displayMetrics);
    }

احصل على الارتفاع والعرض بالبكسل

int width  =displayMetrics.widthPixels;
int height =displayMetrics.heightPixels;

هذه ليست إجابة لـ OP ، حيث أراد أبعاد العرض بالبكسلات الحقيقية. أردت الأبعاد في "بكسل مستقلة الجهاز" ، ووضع إجابات من هنا https://stackoverflow.com/a/17880012/253938 و هنا https://stackoverflow.com/a/665674/253938 خطرت لي هذه:

    DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
    int dpHeight = (int)(displayMetrics.heightPixels / displayMetrics.density + 0.5);
    int dpWidth = (int)(displayMetrics.widthPixels / displayMetrics.density + 0.5);

هناك طريقة غير مستقرة للقيام بذلك باستخدام DisplayMetrics (API 1) ، والتي تتجنب الفوضى المحاولة:

 // initialize the DisplayMetrics object
 DisplayMetrics deviceDisplayMetrics = new DisplayMetrics();

 // populate the DisplayMetrics object with the display characteristics
 getWindowManager().getDefaultDisplay().getMetrics(deviceDisplayMetrics);

 // get the width and height
 screenWidth = deviceDisplayMetrics.widthPixels;
 screenHeight = deviceDisplayMetrics.heightPixels;

أود أن أرفف رمز GetSize مثل هذا:

@SuppressLint("NewApi")
public static Point getScreenSize(Activity a) {
    Point size = new Point();
    Display d = a.getWindowManager().getDefaultDisplay();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        d.getSize(size);
    } else {
        size.x = d.getWidth();
        size.y = d.getHeight();
    }
    return size;
}

يمكنك الحصول على ارتفاع الحجم باستخدام:

getResources().getDisplayMetrics().heightPixels;

و ال العرض الحجم باستخدام

getResources().getDisplayMetrics().widthPixels; 

لمن يبحث عن البعد الشاشة القابل للاستخدام بدون شريط الحالة و شريط العمل (أيضًا بفضل إجابة Swapnil):

DisplayMetrics dm = getResources().getDisplayMetrics();
float screen_w = dm.widthPixels;
float screen_h = dm.heightPixels;

int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resId > 0) {
    screen_h -= getResources().getDimensionPixelSize(resId);
}

TypedValue typedValue = new TypedValue();
if(getTheme().resolveAttribute(android.R.attr.actionBarSize, typedValue, true)){
    screen_h -= getResources().getDimensionPixelSize(typedValue.resourceId);
}

قم أولاً بتحميل ملف XML ثم اكتب هذا الرمز:

setContentView(R.layout.main);      
Display display = getWindowManager().getDefaultDisplay();
final int width = (display.getWidth());
final int height = (display.getHeight());

عرض العرض والارتفاع وفقا دقة الشاشة.

اتبع الأساليب أدناه:

public static int getWidthScreen(Context context) {
    return getDisplayMetrics(context).widthPixels;
}

public static int getHeightScreen(Context context) {
    return getDisplayMetrics(context).heightPixels;
}

private static DisplayMetrics getDisplayMetrics(Context context) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(displayMetrics);
    return displayMetrics;
}

هناك أوقات تحتاج فيها إلى معرفة الأبعاد الدقيقة للمساحة المتاحة للتخطيط عندما تكون في النشاط oncreate. بعد أن اعتقد البعض أنني عملت بهذه الطريقة في القيام بذلك.

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startActivityForResult(new Intent(this, Measure.class), 1);
        // Return without setting the layout, that will be done in onActivityResult.
    }

    @Override
    protected void onActivityResult (int requestCode, int resultCode, Intent data) {
        // Probably can never happen, but just in case.
        if (resultCode == RESULT_CANCELED) {
            finish();
            return;
        }
        int width = data.getIntExtra("Width", -1);
        // Width is now set to the precise available width, and a layout can now be created.            ...
    }
}

public final class Measure extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
       // Create a LinearLayout with a MeasureFrameLayout in it.
        // Just putting a subclass of LinearLayout in works fine, but to future proof things, I do it this way.
        LinearLayout linearLayout = new LinearLayout(this);
        LinearLayout.LayoutParams matchParent = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        MeasureFrameLayout measureFrameLayout = new MeasureFrameLayout(this);
        measureFrameLayout.setLayoutParams(matchParent);
        linearLayout.addView(measureFrameLayout);
        this.addContentView(linearLayout, matchParent);
        // measureFrameLayout will now request this second activity to finish, sending back the width.
    }

    class MeasureFrameLayout extends FrameLayout {
        boolean finished = false;
        public MeasureFrameLayout(Context context) {
            super(context);
        }

        @SuppressLint("DrawAllocation")
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            if (finished) {
                return;
            }
            finished = true;
            // Send the width back as the result.
            Intent data = new Intent().putExtra("Width", MeasureSpec.getSize(widthMeasureSpec));
            Measure.this.setResult(Activity.RESULT_OK, data);
            // Tell this activity to finish, so the result is passed back.
            Measure.this.finish();
        }
    }
}

إذا كنت لا ترغب في إضافة نشاط آخر لسبب ما إلى بيان Android ، فيمكنك القيام بذلك بهذه الطريقة:

public class MainActivity extends Activity {
    static Activity measuringActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        if (extras == null) {
            extras = new Bundle();
        }
        int width = extras.getInt("Width", -2);
        if (width == -2) {
            // First time in, just start another copy of this activity.
            extras.putInt("Width", -1);
            startActivityForResult(new Intent(this, MainActivity.class).putExtras(extras), 1);
            // Return without setting the layout, that will be done in onActivityResult.
            return;
        }
        if (width == -1) {
            // Second time in, here is where the measurement takes place.
            // Create a LinearLayout with a MeasureFrameLayout in it.
            // Just putting a subclass of LinearLayout in works fine, but to future proof things, I do it this way.
            LinearLayout linearLayout = new LinearLayout(measuringActivity = this);
            LinearLayout.LayoutParams matchParent = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            MeasureFrameLayout measureFrameLayout = new MeasureFrameLayout(this);
            measureFrameLayout.setLayoutParams(matchParent);
            linearLayout.addView(measureFrameLayout);
            this.addContentView(linearLayout, matchParent);
            // measureFrameLayout will now request this second activity to finish, sending back the width.
        }
    }

    @Override
    protected void onActivityResult (int requestCode, int resultCode, Intent data) {
        // Probably can never happen, but just in case.
        if (resultCode == RESULT_CANCELED) {
            finish();
            return;
        }
        int width = data.getIntExtra("Width", -3);
        // Width is now set to the precise available width, and a layout can now be created. 
        ...
    }

class MeasureFrameLayout extends FrameLayout {
    boolean finished = false;
    public MeasureFrameLayout(Context context) {
        super(context);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (finished) {
            return;
        }
        finished = true;
        // Send the width back as the result.
        Intent data = new Intent().putExtra("Width", MeasureSpec.getSize(widthMeasureSpec));
        MainActivity.measuringActivity.setResult(Activity.RESULT_OK, data);
        // Tell the (second) activity to finish.
        MainActivity.measuringActivity.finish();
    }
}    

إذا كنت لا تريد أن يكون النفقات العامة لأجهزة Windowsmanagers أو النقاط أو العرض ، فيمكنك الحصول على سمات الارتفاع والعرض لعنصر العرض الأعلى في XML الخاص بك ، شريطة أن يتم ضبط ارتفاعه وعرضه على match_parent. (هذا صحيح طالما أن تخطيطك يأخذ الشاشة بأكملها.)

على سبيل المثال ، إذا بدأ XML الخاص بك بشيء من هذا القبيل:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/entireLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

ثم findViewById(R.id.entireLayout).getWidth() سيعود عرض الشاشة و findViewById(R.id.entireLayout).getHeight() سيعود ارتفاع الشاشة.

لديّ نشاط شاشة دفقة مع خط خطي كعرض جذر له اهل مشتركين لعرضه وارتفاعه. هذا هو الرمز في onCreate() طريقة هذا النشاط. أستخدم هذه التدابير في جميع الأنشطة الأخرى للتطبيق.

int displayWidth = getRawDisplayWidthPreHoneycomb();
int rawDisplayHeight = getRawDisplayHeightPreHoneycomb();
int usableDisplayHeight = rawDisplayHeight - getStatusBarHeight();
pf.setScreenParameters(displayWidth, usableDisplayHeight);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    LinearLayout myView = (LinearLayout) findViewById(R.id.splash_view);
    myView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
            if (left == 0 && top == 0 && right == 0 && bottom == 0) {
                return;
            }
            int displayWidth = Math.min(right, bottom);
            int usableDisplayHeight = Math.max(right, bottom);
            pf.setScreenParameters(displayWidth, usableDisplayHeight);
        }
    });
}

فيما يلي تطبيقات الأساليب التي تراها يتم استدعاؤها أعلاه:

private int getRawDisplayWidthPreHoneycomb() {
    WindowManager windowManager = getWindowManager();
    Display display = windowManager.getDefaultDisplay();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    display.getMetrics(displayMetrics);

    int widthPixels = displayMetrics.widthPixels;
    int heightPixels = displayMetrics.heightPixels;

    return Math.min(widthPixels, heightPixels);
}

private int getRawDisplayHeightPreHoneycomb() {
    WindowManager w = getWindowManager();
    Display d = w.getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    d.getMetrics(metrics);

    int widthPixels = metrics.widthPixels;
    int heightPixels = metrics.heightPixels;

    return Math.max(widthPixels, heightPixels);
}

public int getStatusBarHeight() {
    int statusBarHeight = 0;

    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        statusBarHeight = getResources().getDimensionPixelSize(resourceId);
    }

    return statusBarHeight;
}

ينتج عن هذا ارتفاع وعرض العرض القابل للاستخدام ، باستثناء أي نوع من القضبان (شريط الحالة ، شريط التنقل) ، لجميع إصدارات API وأنواع مختلفة من الأجهزة (الهواتف والأجهزة اللوحية).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top