Example usage for android.view Display getSize

List of usage examples for android.view Display getSize

Introduction

In this page you can find the example usage for android.view Display getSize.

Prototype

public void getSize(Point outSize) 

Source Link

Document

Gets the size of the display, in pixels.

Usage

From source file:com.wojtechnology.sunami.OuterLayout.java

private void updateScreenHeight() {
    Display display = mContext.getWindowManager().getDefaultDisplay();
    Window window = mContext.getWindow();
    Point size = new Point();
    Rect rectangle = new Rect();
    display.getSize(size);
    window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
    mScreenHeight = size.y - rectangle.top;
}

From source file:processing.android.PFragment.java

public void initDimensions() {
    /*//  w  ww .j  a v  a  2 s  .c o m
    metrics = new DisplayMetrics();
    //    getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
    WindowManager wm = getActivity().getWindowManager();
    Display display = wm.getDefaultDisplay();
    display.getRealMetrics(metrics);
    */

    //    metrics = new DisplayMetrics();
    //    getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
    //    display.getRealMetrics(metrics); // API 17 or higher
    //    display.getRealSize(size);

    //    display.getMetrics(metrics);

    size = new Point();
    WindowManager wm = getActivity().getWindowManager();
    Display display = wm.getDefaultDisplay();
    if (Build.VERSION.SDK_INT >= 17) {
        display.getRealSize(size);
    } else if (Build.VERSION.SDK_INT >= 14) {
        // Use undocumented methods getRawWidth, getRawHeight
        try {
            size.x = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
            size.y = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
        } catch (Exception e) {
            display.getSize(size);
        }
    }
}

From source file:own.projects.lemiroapp.GameModeActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setDefaultUncaughtExceptionHandler();

    options = getIntent().getParcelableExtra("own.projects.lemiroapp.Options");

    millSectors = new ImageView[3];

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    screenWidth = size.x;/*w w w .j  av  a 2s .c o m*/

    setContentView(R.layout.activity_main);
    fieldLayout = (GridLayout) findViewById(R.id.field);
    progressText = (TextView) findViewById(R.id.progressText);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    ((LinearLayout) fieldLayout.getParent()).updateViewLayout(fieldLayout,
            new LinearLayout.LayoutParams(screenWidth, screenWidth));

    progressUpdater = new ProgressUpdater(progressBar, this);

    currMove = null;
    remiCount = 20;
    fieldView = new GameBoardView(THIS, fieldLayout);

    init();

    gameThread.start();

}

From source file:a.dev.mobile.thread.MainActivity.java

public int calculateDrawerWidth() {
    // Calculate ActionBar height
    TypedValue tv = new TypedValue();
    int actionBarHeight = 0;
    if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
        actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
    }//from  w w w  . j ava2  s  . c o m
    Display display = getWindowManager().getDefaultDisplay();
    int width;

    if (android.os.Build.VERSION.SDK_INT >= 13) {
        Point size = new Point();
        display.getSize(size);
        width = size.x;

    } else {
        width = display.getWidth(); // deprecated

    }
    return width - actionBarHeight;
}

From source file:kr.wdream.storyshop.AndroidUtilities.java

public static void checkDisplaySize(Context context, Configuration newConfiguration) {
    try {//ww w . j a  v a  2  s .c om
        density = context.getResources().getDisplayMetrics().density;
        Configuration configuration = newConfiguration;
        if (configuration == null) {
            configuration = context.getResources().getConfiguration();
        }
        usingHardwareInput = configuration.keyboard != Configuration.KEYBOARD_NOKEYS
                && configuration.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO;
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (manager != null) {
            Display display = manager.getDefaultDisplay();
            if (display != null) {
                display.getMetrics(displayMetrics);
                display.getSize(displaySize);
            }
        }
        if (configuration.screenWidthDp != Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
            int newSize = (int) Math.ceil(configuration.screenWidthDp * density);
            if (Math.abs(displaySize.x - newSize) > 3) {
                displaySize.x = newSize;
            }
        }
        if (configuration.screenHeightDp != Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
            int newSize = (int) Math.ceil(configuration.screenHeightDp * density);
            if (Math.abs(displaySize.y - newSize) > 3) {
                displaySize.y = newSize;
            }
        }
        FileLog.e("tmessages", "display size = " + displaySize.x + " " + displaySize.y + " "
                + displayMetrics.xdpi + "x" + displayMetrics.ydpi);
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:com.github.chenxiaolong.dualbootpatcher.MainActivity.java

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

    mHandler = new Handler();

    mPrefs = getSharedPreferences("settings", 0);

    if (savedInstanceState != null) {
        mTitle = savedInstanceState.getInt(EXTRA_TITLE);
    }//from   w ww.  j av a2s. com

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open,
            R.string.drawer_close) {
        @Override
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);

            if (mPending != null) {
                mHandler.post(mPending);
                mPending = null;
            }
        }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
    }

    mDrawerView = (NavigationView) findViewById(R.id.left_drawer);
    mDrawerView.setNavigationItemSelectedListener(this);

    // There's a weird performance issue when the drawer is first opened, no matter if we set
    // the background on the nav header RelativeLayout, set the image on an ImageView, or use
    // Picasso to do either asynchronously. By accident, I noticed that using Picasso's resize()
    // method with any dimensions (even the original) works around the performance issue. Maybe
    // something doesn't like PNGs exported from GIMP?
    View header = mDrawerView.inflateHeaderView(R.layout.nav_header);
    ImageView navImage = (ImageView) header.findViewById(R.id.nav_header_image);
    BitmapFactory.Options dimensions = new BitmapFactory.Options();
    dimensions.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(getResources(), R.drawable.material, dimensions);
    Picasso.with(this).load(R.drawable.material).resize(dimensions.outWidth, dimensions.outHeight)
            .into(navImage);

    // Set nav drawer header text
    TextView appName = (TextView) header.findViewById(R.id.nav_header_app_name);
    appName.setText(BuildConfig.APP_NAME_RESOURCE);
    TextView appVersion = (TextView) header.findViewById(R.id.nav_header_app_version);
    appVersion.setText(String.format(getString(R.string.version), BuildConfig.VERSION_NAME));

    // Nav drawer width according to material design guidelines
    // http://www.google.com/design/spec/patterns/navigation-drawer.html
    // https://medium.com/sebs-top-tips/material-navigation-drawer-sizing-558aea1ad266
    final Display display = getWindowManager().getDefaultDisplay();
    final Point size = new Point();
    display.getSize(size);

    final ViewGroup.LayoutParams params = mDrawerView.getLayoutParams();
    int toolbarHeight = getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);
    params.width = Math.min(size.x - toolbarHeight, 6 * toolbarHeight);
    mDrawerView.setLayoutParams(params);

    if (savedInstanceState != null) {
        mFragment = savedInstanceState.getInt(EXTRA_FRAGMENT);

        showFragment();

        mDrawerItemSelected = savedInstanceState.getInt(EXTRA_SELECTED_ITEM);
    } else {
        String[] initialScreens = getResources().getStringArray(R.array.initial_screen_entry_values);
        String initialScreen = mPrefs.getString("initial_screen", null);
        if (initialScreen == null || !ArrayUtils.contains(initialScreens, initialScreen)) {
            initialScreen = INITIAL_SCREEN_ABOUT;
            Editor e = mPrefs.edit();
            e.putString("initial_screen", initialScreen);
            e.apply();
        }

        int navId;
        switch (initialScreen) {
        case INITIAL_SCREEN_ABOUT:
            navId = R.id.nav_about;
            break;
        case INITIAL_SCREEN_ROMS:
            navId = R.id.nav_roms;
            break;
        case INITIAL_SCREEN_PATCHER:
            navId = R.id.nav_patch_zip;
            break;
        default:
            throw new IllegalStateException("Invalid initial screen value");
        }

        // Show about screen by default
        mDrawerItemSelected = navId;
    }

    onDrawerItemClicked(mDrawerItemSelected, false);

    refreshOptionalItems();

    // Open drawer on first start
    new Thread() {
        @Override
        public void run() {
            boolean isFirstStart = mPrefs.getBoolean("first_start", true);
            if (isFirstStart) {
                mDrawerLayout.openDrawer(mDrawerView);
                Editor e = mPrefs.edit();
                e.putBoolean("first_start", false);
                e.apply();
            }
        }
    }.start();
}

From source file:com.nextgis.mobile.fragment.LayersFragment.java

/**
 * Users of this fragment must call this method to set up the navigation drawer interactions.
 *
 * @param fragmentId//w  ww.  ja v a2s  .c  o m
 *         The android:id of this fragment in its activity's layout.
 * @param drawerLayout
 *         The DrawerLayout containing this fragment's UI.
 */
public void setUp(int fragmentId, DrawerLayout drawerLayout, final MapDrawable map) {
    MainActivity activity = (MainActivity) getActivity();
    mFragmentContainerView = activity.findViewById(fragmentId);

    Display display = activity.getWindowManager().getDefaultDisplay();

    int displayWidth;
    if (android.os.Build.VERSION.SDK_INT >= 13) {
        Point size = new Point();
        display.getSize(size);
        displayWidth = size.x;
    } else {
        displayWidth = display.getWidth();
    }

    ViewGroup.LayoutParams params = mFragmentContainerView.getLayoutParams();
    if (params.width >= displayWidth) {
        params.width = (int) (displayWidth * 0.8);
    }
    mFragmentContainerView.setLayoutParams(params);

    final MapFragment mapFragment = activity.getMapFragment();
    mListAdapter = new LayersListAdapter(activity, mapFragment.mMap);
    mListAdapter.setDrawer(drawerLayout);
    mListAdapter.setOnPencilClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mapFragment.hasEdits()) {
                if (mapFragment.mFinishListener != null)
                    mapFragment.mFinishListener.onClick(null);
                return;
            }

            AlertDialog builder = new AlertDialog.Builder(getContext()).setTitle(R.string.save)
                    .setMessage(R.string.has_edits)
                    .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mapFragment.saveEdits();
                            mapFragment.setMode(MapFragment.MODE_NORMAL);
                        }
                    }).setNegativeButton(R.string.discard, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mapFragment.cancelEdits();
                            mapFragment.setMode(MapFragment.MODE_NORMAL);
                        }
                    }).create();
            builder.show();
        }
    });
    mListAdapter.setOnLayerEditListener(new LayersListAdapter.onEdit() {
        @Override
        public void onLayerEdit(ILayer layer) {
            IGISApplication application = (IGISApplication) getActivity().getApplication();
            application.sendEvent(GA_LAYER, GA_EDIT, GA_MENU);
            mapFragment.onFinishChooseLayerDialog(MapFragment.EDIT_LAYER, layer);
            toggle();
        }
    });
    mapFragment.setOnModeChangeListener(new MapFragment.onModeChange() {
        @Override
        public void onModeChangeListener() {
            mListAdapter.notifyDataSetChanged();
        }
    });

    mLayersListView = (ReorderedLayerView) mFragmentContainerView.findViewById(R.id.layer_list);
    mLayersListView.setAdapter(mListAdapter);
    mLayersListView.setDrawer(drawerLayout);

    mDrawerLayout = drawerLayout;

    // set a custom shadow that overlays the main content when the drawer opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the navigation drawer and the action bar app icon.

    mDrawerToggle = new ActionBarDrawerToggle(getActivity(), // host Activity
            mDrawerLayout, // DrawerLayout object
            //                R.drawable.ic_drawer,             // nav drawer image to replace 'Up' caret
            R.string.layers_drawer_open,
            // "open drawer" description for accessibility
            R.string.layers_drawer_close
    // "close drawer" description for accessibility
    ) {
        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            if (!isAdded()) {
                return;
            }

            getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            if (!isAdded()) {
                return;
            }

            setupSyncOptions();
            getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }
    };

    // Defer code dependent on restoration of previous instance state.
    syncState();
}

From source file:com.mumu.joshautomation.HeadService.java

private void initGameLibrary() {
    int w, h;//from  ww  w .  j a  v  a2 s .  c  o m
    int userWidth, userHeight, userAmbValue, userTouchShift;
    int userScreenXOffset, userScreenYOffset, userWaitTransactTime;

    // try to get user's setting
    try {
        userWidth = Integer.parseInt(mAPV.getPrefs().getString("userSetWidth", "0"));
        userHeight = Integer.parseInt(mAPV.getPrefs().getString("userSetHeight", "0"));
        userAmbValue = Integer.parseInt(mAPV.getPrefs().getString("userAmbValue", "0"));
        userTouchShift = Integer.parseInt(mAPV.getPrefs().getString("userSetTouchShift", "0"));
        userScreenXOffset = Integer.parseInt(mAPV.getPrefs().getString("userSetScreenXOffset", "0"));
        userScreenYOffset = Integer.parseInt(mAPV.getPrefs().getString("userSetScreenYOffset", "0"));
        userWaitTransactTime = Integer
                .parseInt(mAPV.getPrefs().getString("userSetWaitTransactionDoneTime", "0"));
    } catch (NumberFormatException e) {
        Log.e(TAG, "Setting value format error: " + e.getMessage());
        userWidth = 0;
        userHeight = 0;
        userAmbValue = 0;
        userTouchShift = 0;
        userScreenXOffset = 0;
        userScreenYOffset = 0;
        userWaitTransactTime = 0;
    }

    // Initial DefinitionLoader
    DefinitionLoader.getInstance().setResources(mContext.getResources());

    Display display = mWindowManager.getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);

    // we always treat the short edge as width
    // TODO: we need to find a new way to get actual panel width and height
    if (size.x > size.y) {
        w = size.y;
        if (size.x > 2000)
            h = 2160;
        else
            h = size.x;
    } else {
        w = size.x;
        if (size.y > 2000)
            h = 2160;
        else
            h = size.y;
    }

    mGL = JoshGameLibrary.getInstance();
    mGL.setContext(mContext);

    // Check if user override settings
    if (userWidth != 0 && userHeight != 0)
        mGL.setScreenDimension(userWidth, userHeight);
    else
        mGL.setScreenDimension(w, h);

    mGL.getCaptureService().setChatty(mAPV.getPrefs().getBoolean("captureServiceChatty", false));

    if (userAmbValue != 0)
        mGL.setAmbiguousRange(new int[] { userAmbValue, userAmbValue, userAmbValue });
    else
        mGL.setAmbiguousRange(new int[] { JoshGameLibrary.DEFAULT_AMBIGUOUS_VALUE,
                JoshGameLibrary.DEFAULT_AMBIGUOUS_VALUE, JoshGameLibrary.DEFAULT_AMBIGUOUS_VALUE });

    if (userScreenXOffset != 0 || userScreenYOffset != 0)
        mGL.setScreenOffset(userScreenXOffset, userScreenYOffset, ScreenPoint.SO_Portrait);

    if (userTouchShift != 0)
        mGL.setTouchShift(userTouchShift);
    else
        mGL.setTouchShift(JoshGameLibrary.DEFAULT_TOUCH_SHIFT);

    if (userWaitTransactTime != 0)
        mGL.setWaitTransactionTime(userWaitTransactTime);
    else
        mGL.setWaitTransactionTime(JoshGameLibrary.DEFAULT_WAIT_TRANSACT_TIME);

    if (mAPV.getPrefs().getBoolean("ssEnabled", false)) {
        String pn = mAPV.getPrefs().getString("ssPackageName", "");
        String sn = mAPV.getPrefs().getString("ssServiceName", "");
        String in = mAPV.getPrefs().getString("ssInterfaceName", "");
        int code = Integer.parseInt(mAPV.getPrefs().getString("ssTransactCode", "0"));
        mGL.setHackParams(pn, sn, in, code);
        mGL.setHackSS(true);
    } else {
        mGL.setHackSS(false);
    }

    mGL.getCaptureService().setChatty(mAPV.getPrefs().getBoolean("captureServiceChatty", false));

    mAutoJobHandler = AutoJobHandler.getHandler();

    if (!mAutoJobAdded) {
        mAutoJobHandler.addJob(new LoopBattleJob());
        mAutoJobHandler.addJob(new AutoBattleJob());
        mAutoJobHandler.addJob(new PureBattleJob());
        mAutoJobHandler.addJob(new NewFlushJob());
        mAutoJobHandler.addJob(new TWAutoLoginJob());
        mAutoJobHandler.addJob(new ShinobiLoopBattleJob());
        mAutoJobHandler.addJob(new FlushJob());
        mAutoJobHandler.addJob(new FlushMoneyJob());
        mAutoJobHandler.addJob(new ROAutoDrinkJob());
        mAutoJobHandler.addJob(new AutoBoxJob());

        mAutoJobHandler.setJobEventListener(LoopBattleJob.jobName, this);
        mAutoJobHandler.setJobEventListener(PureBattleJob.jobName, this);
        mAutoJobHandler.setJobEventListener(AutoBattleJob.jobName, this);
        mAutoJobHandler.setJobEventListener(NewFlushJob.jobName, this);
        mAutoJobHandler.setJobEventListener(TWAutoLoginJob.jobName, this);
        mAutoJobHandler.setJobEventListener(ShinobiLoopBattleJob.jobName, this);
        mAutoJobHandler.setJobEventListener(FlushJob.jobName, this);
        mAutoJobHandler.setJobEventListener(FlushMoneyJob.jobName, this);
        mAutoJobHandler.setJobEventListener(AutoBoxJob.jobName, this);

        //add service itself to job
        mAutoJobHandler.setExtra(LoopBattleJob.jobName, this);
        mAutoJobHandler.setExtra(ShinobiLoopBattleJob.jobName, this);
        mAutoJobHandler.setExtra(FlushJob.jobName, this);
        mAutoJobHandler.setExtra(FlushMoneyJob.jobName, this);
        mAutoJobAdded = true;
    }
}

From source file:com.shopify.buy.ui.ProductDetailsFragmentView.java

/**
 * Get the display size./*from  w  ww.ja v a  2s. com*/
 * @return display size in {@link Point}.
 */
private Point getDisplaySize() {
    Point pt = new Point();

    if (DeviceUtils.isTablet(getResources())) {
        // For tablets we have explicitly set a dialog window size, so lets return that here
        pt.x = fragment.getActivity().getWindow().getAttributes().width;
        pt.y = fragment.getActivity().getWindow().getAttributes().height;
    } else {
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        display.getSize(pt);
    }

    return pt;
}

From source file:org.openqa.selendroid.server.model.DefaultSelendroidDriver.java

@Override
@SuppressWarnings("deprecation")
public byte[] takeScreenshot() {
    ViewHierarchyAnalyzer viewAnalyzer = ViewHierarchyAnalyzer.getDefaultInstance();

    // TODO ddary review later, but with getRecentDecorView() it seems to work better
    // long drawingTime = 0;
    // View container = null;
    // for (View view : viewAnalyzer.getTopLevelViews()) {
    // if (view != null && view.isShown() && view.hasWindowFocus()
    // && view.getDrawingTime() > drawingTime) {
    // container = view;
    // drawingTime = view.getDrawingTime();
    // }//from ww w.  j av a2s .c  o  m
    // }
    // final View mainView = container;
    final View mainView = viewAnalyzer.getRecentDecorView();
    if (mainView == null) {
        throw new SelendroidException("No open windows.");
    }
    done = false;
    long end = System.currentTimeMillis() + serverInstrumentation.getAndroidWait().getTimeoutInMillis();
    final byte[][] rawPng = new byte[1][1];
    ServerInstrumentation.getInstance().getCurrentActivity().runOnUiThread(new Runnable() {
        public void run() {
            synchronized (syncObject) {
                Display display = serverInstrumentation.getCurrentActivity().getWindowManager()
                        .getDefaultDisplay();
                Point size = new Point();
                try {
                    display.getSize(size);
                } catch (NoSuchMethodError ignore) { // Older than api level 13
                    size.x = display.getWidth();
                    size.y = display.getHeight();
                }

                // Get root view
                View view = mainView.getRootView();

                // Create the bitmap to use to draw the screenshot
                final Bitmap bitmap = Bitmap.createBitmap(size.x, size.y, Bitmap.Config.ARGB_8888);
                final Canvas canvas = new Canvas(bitmap);

                // Get current theme to know which background to use
                final Activity activity = serverInstrumentation.getCurrentActivity();
                final Theme theme = activity.getTheme();
                final TypedArray ta = theme
                        .obtainStyledAttributes(new int[] { android.R.attr.windowBackground });
                final int res = ta.getResourceId(0, 0);
                final Drawable background = activity.getResources().getDrawable(res);

                // Draw background
                background.draw(canvas);

                // Draw views
                view.draw(canvas);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                if (!bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)) {
                    throw new RuntimeException("Error while compressing screenshot image.");
                }
                try {
                    stream.flush();
                    stream.close();
                } catch (IOException e) {
                    throw new RuntimeException("I/O Error while capturing screenshot: " + e.getMessage());
                } finally {
                    Closeable closeable = (Closeable) stream;
                    try {
                        if (closeable != null) {
                            closeable.close();
                        }
                    } catch (IOException ioe) {
                        // ignore
                    }
                }
                rawPng[0] = stream.toByteArray();
                mainView.destroyDrawingCache();
                done = true;
                syncObject.notify();
            }
        }
    });

    waitForDone(end, serverInstrumentation.getAndroidWait().getTimeoutInMillis(), "Failed to take screenshot.");
    return rawPng[0];
}