get Screen Width and check its orientation - Android User Interface

Android examples for User Interface:Screen Orientation

Description

get Screen Width and check its orientation

Demo Code


//package com.java2s;
import android.content.Context;
import android.content.res.Configuration;

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

public class Main {
    public static final String TAG = "CLDeviceUtil";

    public static int getScreenWidth(Context context) {
        int screenSizeOne = -1;
        int screenSizeTwo = -1;

        if (screenSizeOne <= 0 || screenSizeTwo <= 0) {
            DisplayMetrics dm = new DisplayMetrics();
            WindowManager wm = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            if (wm != null) {
                wm.getDefaultDisplay().getMetrics(dm);
            }//from  w  w w  .  j a v  a2 s .  c om
            screenSizeOne = dm.widthPixels;
            screenSizeTwo = dm.heightPixels;
        }

        Configuration conf = context.getResources().getConfiguration();
        switch (conf.orientation) {
        case Configuration.ORIENTATION_LANDSCAPE:
            return screenSizeOne > screenSizeTwo ? screenSizeOne
                    : screenSizeTwo;
        case Configuration.ORIENTATION_PORTRAIT:
            return screenSizeOne < screenSizeTwo ? screenSizeOne
                    : screenSizeTwo;
        default:
            Log.e(TAG, "can't get screen width!");
        }
        return screenSizeOne;
    }
}

Related Tutorials