android.util.DisplayMetrics Java Examples

The following examples show how to use android.util.DisplayMetrics. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RemoveViewTest.java    From Magnet with MIT License 6 votes vote down vote up
@Test public void testOnMoveXSmallerThanMidpoint() {
  // given
  DisplayMetrics displayMetricsMock = mock(DisplayMetrics.class);
  Resources resourcesMock = mock(Resources.class);
  doReturn(contextMock).when(buttonMock).getContext();
  doReturn(resourcesMock).when(contextMock).getResources();
  doReturn(displayMetricsMock).when(resourcesMock).getDisplayMetrics();
  displayMetricsMock.widthPixels = 400;

  int x = 100;
  int midpoint = displayMetricsMock.widthPixels / 2;
  int xDelta = x - midpoint;
  int xTransformed = Math.abs(xDelta * 100 / midpoint);
  int bottomPadding = buttonBottomPaddingTest - (xTransformed / 5);

  // when
  removeView.onMove(x, 100);

  // then
  verify(buttonMock).setPadding(0, 0, xTransformed, bottomPadding);
}
 
Example #2
Source File: ShortyzActivity.java    From shortyz with GNU General Public License v3.0 6 votes vote down vote up
protected Bitmap createBitmap(String fontFile, String character){
      DisplayMetrics metrics = new DisplayMetrics();
      getWindowManager().getDefaultDisplay().getMetrics(metrics);
int dpi = Math.round(160F * metrics.density);
      int size = dpi / 2;
Bitmap bitmap = Bitmap.createBitmap(size , size, Bitmap.Config.ARGB_8888);
      Canvas canvas = new Canvas(bitmap);
      Paint p = new Paint();
      p.setColor(Color.WHITE);
      p.setStyle(Paint.Style.FILL);
      p.setTypeface(Typeface.createFromAsset(getAssets(), fontFile));
      p.setTextSize(size);
      p.setAntiAlias(true);
      p.setTextAlign(Paint.Align.CENTER);
      canvas.drawText(character, size/2, size - size / 9, p );
      return bitmap;

  }
 
Example #3
Source File: StickyListAdapter.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
public StickyListAdapter(Context context, List<FriendEntry> list, boolean isSelectMode, HorizontalScrollView scrollView, GridView gridView, CreateGroupAdapter groupAdapter) {
    this.mContext = context;
    this.mData = list;
    this.mIsSelectMode = isSelectMode;
    this.scrollViewSelected = scrollView;
    this.imageSelectedGridView = gridView;
    this.mGroupAdapter = groupAdapter;
    this.mInflater = LayoutInflater.from(context);
    Activity activity = (Activity) mContext;
    DisplayMetrics dm = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    mDensity = dm.density;
    mSelectedNum = (TextView) activity.findViewById(R.id.selected_num);
    mSectionIndices = getSectionIndices();
    mSectionLetters = getSectionLetters();
}
 
Example #4
Source File: MySwipeRefreshLayout.java    From Cotable with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor that is called when inflating SwipeRefreshLayout from XML.
 *
 * @param context
 * @param attrs
 */
public MySwipeRefreshLayout(Context context, AttributeSet attrs) {
    super(context, attrs);

    mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();

    mMediumAnimationDuration = getResources().getInteger(
            android.R.integer.config_mediumAnimTime);

    setWillNotDraw(false);
    mDecelerateInterpolator = new DecelerateInterpolator(DECELERATE_INTERPOLATION_FACTOR);

    final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
    setEnabled(a.getBoolean(0, true));
    a.recycle();

    final DisplayMetrics metrics = getResources().getDisplayMetrics();
    mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);
    mCircleHeight = (int) (CIRCLE_DIAMETER * metrics.density);

    createProgressView();
    ViewCompat.setChildrenDrawingOrderEnabled(this, true);
    // the absolute offset has to take into account that the circle starts at an offset
    mSpinnerFinalOffset = DEFAULT_CIRCLE_TARGET * metrics.density;
    mTotalDragDistance = mSpinnerFinalOffset;
}
 
Example #5
Source File: ScreenResolution.java    From video-player with MIT License 6 votes vote down vote up
/**
 * Gets resolution on old devices.
 * Tries the reflection to get the real resolution first.
 * Fall back to getDisplayMetrics if the above method failed.
 * */
private static Pair<Integer, Integer> getRealResolutionOnOldDevice(Context ctx) {
  try{
    WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    Method mGetRawWidth = Display.class.getMethod("getRawWidth");
    Method mGetRawHeight = Display.class.getMethod("getRawHeight");
    Integer realWidth = (Integer) mGetRawWidth.invoke(display);
    Integer realHeight = (Integer) mGetRawHeight.invoke(display);
    return new Pair<Integer, Integer>(realWidth, realHeight);
  }
  catch (Exception e) {
    DisplayMetrics disp = ctx.getResources().getDisplayMetrics();
    return new Pair<Integer, Integer>(disp.widthPixels, disp.heightPixels);
  }
}
 
Example #6
Source File: DeviceProfile.java    From LB-Launcher with Apache License 2.0 6 votes vote down vote up
private int getDeviceOrientation(Context context) {
    WindowManager windowManager =  (WindowManager)
            context.getSystemService(Context.WINDOW_SERVICE);
    Resources resources = context.getResources();
    DisplayMetrics dm = resources.getDisplayMetrics();
    Configuration config = resources.getConfiguration();
    int rotation = windowManager.getDefaultDisplay().getRotation();

    boolean isLandscape = (config.orientation == Configuration.ORIENTATION_LANDSCAPE) &&
            (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180);
    boolean isRotatedPortrait = (config.orientation == Configuration.ORIENTATION_PORTRAIT) &&
            (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270);
    if (isLandscape || isRotatedPortrait) {
        return CellLayout.LANDSCAPE;
    } else {
        return CellLayout.PORTRAIT;
    }
}
 
Example #7
Source File: PXNamedMediaExpression.java    From pixate-freestyle-android with Apache License 2.0 6 votes vote down vote up
private float getFloatValue(Context context) {
    if (value instanceof Number) {
        return ((Number) value).floatValue();
    } else if (value instanceof String) {
        return Float.parseFloat(value.toString());
    } else if (value instanceof PXDimension) {
        PXDimension dimension = (PXDimension) value;

        if (dimension.isLength()) {
            DisplayMetrics metrics = getDisplayMetrics(context);
            return dimension.points(metrics).getNumber();
        } else {
            return 0.0f;
        }
    } else {
        return 0.0f;
    }
}
 
Example #8
Source File: ListenerModule.java    From leanback-showcase with Apache License 2.0 6 votes vote down vote up
@PerFragment
@Provides
@IntoMap
@ListenerModuleKey(LiveDataFragment.class)
public OnItemViewSelectedListener provideOnItemViewSelectedListener(final Activity activity,
        final DisplayMetrics metrics, final BackgroundManager backgroundManager,
        final RequestOptions defaultPlaceHolder, final Drawable finalDrawable, final Handler mainHandler) {
    return new OnItemViewSelectedListener() {
        @Override
        public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item,
                RowPresenter.ViewHolder rowViewHolder, Row row) {
            VideoEntity selectedVideo = (VideoEntity) item;
            RunnableClass backgroundRunnable = new RunnableClass(selectedVideo, activity,
                    metrics, backgroundManager, defaultPlaceHolder, finalDrawable);

            if (lastTime != null) {
                mainHandler.removeCallbacks(lastTime);
            }
            mainHandler.postDelayed(backgroundRunnable, BACKGROUND_UPDATE_DELAY);
            lastTime = backgroundRunnable;
        }
    };
}
 
Example #9
Source File: PointView.java    From AdPlayBanner with Apache License 2.0 6 votes vote down vote up
private void setDefault(float size) {
    setGravity(Gravity.CENTER);
    setTextColor(Color.WHITE);

    DisplayMetrics metrics = getResources().getDisplayMetrics();
    if (size <= 0) {
        mSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14, metrics);
    } else {
        mSize = size;
    }

    if (metrics.density <= 1.5) {
        setTextSize(TypedValue.COMPLEX_UNIT_DIP, 9);
    } else {
        setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
    }

    int paddingLeft = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, metrics);
    int paddingRight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, metrics);

    setPadding(paddingLeft, 0, paddingRight, 0);

    change();
}
 
Example #10
Source File: RotateView.java    From WanAndroid with Apache License 2.0 6 votes vote down vote up
public RotateView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RotateView);
    BitmapDrawable bitmapDrawable = (BitmapDrawable) array.getDrawable(R.styleable.RotateView_viewBackgound2);
    array.recycle();

    if (bitmapDrawable != null) {

        bitmap = bitmapDrawable.getBitmap();
        byte[] bytes = BitmapUtil.bitmap2Bytes(bitmap);
        bitmap = BitmapUtil.resizeBitmapBytes(bytes);
    }else {
        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    }

    camera = new Camera();
    paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    float newZ = -metrics.density * 6;
    camera.setLocation(0, 0, newZ);
}
 
Example #11
Source File: CastDetailsBiography.java    From moviedb-android with Apache License 2.0 6 votes vote down vote up
/**
 * Called to have the fragment instantiate its user interface view.
 *
 * @param inflater           sets the layout for the current view.
 * @param container          the container which holds the current view.
 * @param savedInstanceState If non-null, this fragment is being re-constructed from a previous saved state as given here.
 *                           Return the View for the fragment's UI, or null.
 */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    View rootView = inflater.inflate(R.layout.castdetailsbiography, container, false);
    activity = ((MainActivity) getActivity());
    biography = (TextView) rootView.findViewById(R.id.biographyContent);
    scrollView = (ObservableScrollView) rootView.findViewById(R.id.castdetailsbiography);
    new Handler().post(new Runnable() {
        @Override
        public void run() {
            View toolbarView = activity.findViewById(R.id.toolbar);
            if (toolbarView != null) {
                int toolbarHeight = toolbarView.getHeight();
                DisplayMetrics displayMetrics = activity.getResources().getDisplayMetrics();
                int height = displayMetrics.heightPixels;
                biography.setMinHeight(height + toolbarHeight);
            }
        }
    });

    return rootView;
}
 
Example #12
Source File: BubbleActivity.java    From coursera-android with MIT License 5 votes vote down vote up
public BubbleView(Context context, Bitmap bitmap) {
	super(context);

	mBitmapHeightAndWidth = (int) getResources().getDimension(
			R.dimen.image_height_width);
	this.mBitmap = Bitmap.createScaledBitmap(bitmap,
			mBitmapHeightAndWidth, mBitmapHeightAndWidth, false);

	mBitmapHeightAndWidthAdj = mBitmapHeightAndWidth / 2;

	mDisplay = new DisplayMetrics();
	BubbleActivity.this.getWindowManager().getDefaultDisplay()
			.getMetrics(mDisplay);
	mDisplayWidth = mDisplay.widthPixels;
	mDisplayHeight = mDisplay.heightPixels;

	Random r = new Random();
	mX = (float) r.nextInt(mDisplayHeight);
	mY = (float) r.nextInt(mDisplayWidth);
	mDx = (float) r.nextInt(mDisplayHeight) / mDisplayHeight;
	mDx *= r.nextInt(2) == 1 ? MOVE_STEP : -1 * MOVE_STEP;
	mDy = (float) r.nextInt(mDisplayWidth) / mDisplayWidth;
	mDy *= r.nextInt(2) == 1 ? MOVE_STEP : -1 * MOVE_STEP;
	mRotation = 1.0f;

	mPainter.setAntiAlias(true);

	mSurfaceHolder = getHolder();
	mSurfaceHolder.addCallback(this);
}
 
Example #13
Source File: UnreadMsgUtils.java    From imsdk-android with MIT License 5 votes vote down vote up
public static void show(MsgView msgView, int num) {
    if (msgView == null) {
        return;
    }
    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) msgView.getLayoutParams();
    DisplayMetrics dm = msgView.getResources().getDisplayMetrics();
    msgView.setVisibility(View.VISIBLE);
    if (num <= 0) {//圆点,设置默认宽高
        msgView.setStrokeWidth(0);
        msgView.setText("");

        lp.width = (int) (8 * dm.density);
        lp.height = (int) (8 * dm.density);
        msgView.setLayoutParams(lp);
    } else {
        lp.height = (int) (18 * dm.density);
        if (num > 0 && num < 10) {//圆
            lp.width = (int) (18 * dm.density);
            msgView.setText(num + "");
        } else if (num > 9 && num < 100) {//圆角矩形,圆角是高度的一半,设置默认padding
            lp.width = RelativeLayout.LayoutParams.WRAP_CONTENT;
            msgView.setPadding((int) (6 * dm.density), 0, (int) (6 * dm.density), 0);
            msgView.setText(num + "");
        } else {//数字超过两位,显示99+
            lp.width = RelativeLayout.LayoutParams.WRAP_CONTENT;
            msgView.setPadding((int) (6 * dm.density), 0, (int) (6 * dm.density), 0);
            msgView.setText("99+");
        }
        msgView.setLayoutParams(lp);
    }
}
 
Example #14
Source File: LegacyEarthSharedState.java    From earth with GNU General Public License v3.0 5 votes vote down vote up
public int getResolution() {
    if (!BuildConfig.USE_OXO_SERVER) {
        return 550;
    }

    int resolution = preferences.getInt("resolution", 0);

    if (resolution == 0) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        resolution = Resolutions.findBestResolution(metrics);
    }

    return resolution;
}
 
Example #15
Source File: RingView.java    From echo with GNU General Public License v3.0 5 votes vote down vote up
private void init() {
    setWillNotDraw(false);
    paint.setColor(0xff402400);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeCap(Paint.Cap.BUTT);
    final Resources resources = getResources();
    if(resources != null) {
        final DisplayMetrics displayMetrics = resources.getDisplayMetrics();
        ringWidth = displayMetrics.density * 10;
        Log.d(TAG, "density: " + displayMetrics.density);
        Log.d(TAG, "densityDpi: " + displayMetrics.densityDpi);
        Log.d(TAG, "scaledDensity: " + displayMetrics.scaledDensity);
    } else {
        ringWidth = 10;
    }
    paint.setStrokeWidth(ringWidth);
    Ring ring;
    ring = new Ring();
    ring.ticks = 1;
    ring.max = 100;
    ring.value = 100;
    rings.add(ring);
    ring = new Ring();
    ring.ticks = 60;
    ring.max = 10;
    ring.value = 8;
    rings.add(ring);
    ring = new Ring();
    ring.ticks = 60;
    ring.max = 100;
    ring.value = 10;
    rings.add(ring);
}
 
Example #16
Source File: SizeUtils.java    From Matisse with Apache License 2.0 5 votes vote down vote up
/**
 * 获取屏幕尺寸与密度.
 * @param context the context
 * @return mDisplayMetrics
 */
public static DisplayMetrics getDisplayMetrics(Context context) {
    Resources mResources;
    if (context == null) {
        mResources = Resources.getSystem();
    } else {
        mResources = context.getResources();
    }
    //DisplayMetrics{density=1.5, width=480, height=854, scaledDensity=1.5, xdpi=160.421, ydpi=159.497}
    //DisplayMetrics{density=2.0, width=720, height=1280, scaledDensity=2.0, xdpi=160.42105, ydpi=160.15764}
    DisplayMetrics mDisplayMetrics = mResources.getDisplayMetrics();
    return mDisplayMetrics;
}
 
Example #17
Source File: DeviceInfo.java    From proofmode with GNU General Public License v3.0 5 votes vote down vote up
public static String getDeviceInch(Context activity) {
    try {
        DisplayMetrics displayMetrics = activity.getResources().getDisplayMetrics();

        float yInches = displayMetrics.heightPixels / displayMetrics.ydpi;
        float xInches = displayMetrics.widthPixels / displayMetrics.xdpi;
        double diagonalInches = Math.sqrt(xInches * xInches + yInches * yInches);
        return String.valueOf(diagonalInches);
    } catch (Exception e) {
        return "-1";
    }
}
 
Example #18
Source File: WaypointV2ActionDialog.java    From Android-GSDemo-Gaode-Map with MIT License 5 votes vote down vote up
@Override
public void onStart() {
    super.onStart();
    DisplayMetrics dm = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
    getDialog().getWindow().setLayout((int) (dm.widthPixels * 0.9), (int) (dm.heightPixels * 0.9));

}
 
Example #19
Source File: AptoideUtils.java    From aptoide-client with GNU General Public License v2.0 5 votes vote down vote up
public static int getDensityDpi(Context context) {

            DisplayMetrics metrics = new DisplayMetrics();
            WindowManager manager = (WindowManager) context.getSystemService(Service.WINDOW_SERVICE);
            manager.getDefaultDisplay().getMetrics(metrics);

            int dpi = metrics.densityDpi;


            if (dpi <= 120) {
                dpi = 120;
            } else if (dpi <= 160) {
                dpi = 160;
            } else if (dpi <= 213) {
                dpi = 213;
            } else if (dpi <= 240) {
                dpi = 240;
            } else if (dpi <= 320) {
                dpi = 320;
            } else if (dpi <= 480) {
                dpi = 480;
            } else {
                dpi = 640;
            }

            return dpi;
        }
 
Example #20
Source File: PercentLinearLayout.java    From android-percent-support-extend with Apache License 2.0 5 votes vote down vote up
private int getScreenHeight()
{
    WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics outMetrics = new DisplayMetrics();
    wm.getDefaultDisplay().getMetrics(outMetrics);
    return outMetrics.heightPixels;
}
 
Example #21
Source File: AppRenderer.java    From VuforiaLibGDX with MIT License 5 votes vote down vote up
private void storeScreenDimensions()
{
    // Query display dimensions:
    Point size = new Point();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
    {
        mActivityRef.get().getWindowManager().getDefaultDisplay().getRealSize(size);
    }
    else
    {
        WindowManager windowManager = (WindowManager) mActivityRef.get().getSystemService(Context.WINDOW_SERVICE);

        if (windowManager != null)
        {
            DisplayMetrics metrics = new DisplayMetrics();
            Display display = windowManager.getDefaultDisplay();
            display.getMetrics(metrics);

            size.x = metrics.widthPixels;
            size.y = metrics.heightPixels;
        }
        else
        {
            Log.e(LOGTAG, "Could not get display metrics!");
            size.x = 0;
            size.y = 0;
        }
    }

    mScreenWidth = size.x;
    mScreenHeight = size.y;
}
 
Example #22
Source File: Device.java    From react-native-android-vitamio with MIT License 5 votes vote down vote up
public static String getScreenFeatures(Context ctx) {
  StringBuilder sb = new StringBuilder();
  DisplayMetrics disp = ctx.getResources().getDisplayMetrics();
  sb.append(getPair("screen_density", "" + disp.density));
  sb.append(getPair("screen_density_dpi", "" + disp.densityDpi));
  sb.append(getPair("screen_height_pixels", "" + disp.heightPixels));
  sb.append(getPair("screen_width_pixels", "" + disp.widthPixels));
  sb.append(getPair("screen_scaled_density", "" + disp.scaledDensity));
  sb.append(getPair("screen_xdpi", "" + disp.xdpi));
  sb.append(getPair("screen_ydpi", "" + disp.ydpi));
  return sb.toString();
}
 
Example #23
Source File: AttachPopupWindow.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 计算高度和宽度
 * 宽度和屏幕一样
 * 高度是60%的屏幕
 * @param context
 */
private void calWidthAndHeight(Context context) {
    WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics metrics = new DisplayMetrics();
    windowManager.getDefaultDisplay().getMetrics(metrics);
    width = metrics.widthPixels;
    height = (int) (metrics.heightPixels * 0.6 );
}
 
Example #24
Source File: StreamFragment.java    From Twire with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets a Rect representing the usable area of the screen
 *
 * @return A Rect representing the usable area of the screen
 */
public static Rect getScreenRect(Activity activity) {
    if (activity != null) {
        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        Point size = new Point();
        int width, height;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && activity.isInMultiWindowMode()) {
                display.getMetrics(metrics);
            } else {
                display.getRealMetrics(metrics);
            }

            width = metrics.widthPixels;
            height = metrics.heightPixels;
        } else {
            display.getSize(size);
            width = size.x;
            height = size.y;
        }

        return new Rect(0, 0, Math.min(width, height), Math.max(width, height) - totalVerticalInset);
    }

    return new Rect();
}
 
Example #25
Source File: Util.java    From floatingsearchview with Apache License 2.0 5 votes vote down vote up
public static int getScreenWidth(Activity activity) {

        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        display.getMetrics(outMetrics);

        return outMetrics.widthPixels;
    }
 
Example #26
Source File: ScreenUtils.java    From AndroidUtilCode with Apache License 2.0 5 votes vote down vote up
/**
 * Return the bitmap of screen.
 *
 * @param activity          The activity.
 * @param isDeleteStatusBar True to delete status bar, false otherwise.
 * @return the bitmap of screen
 */
public static Bitmap screenShot(@NonNull final Activity activity, boolean isDeleteStatusBar) {
    View decorView = activity.getWindow().getDecorView();
    boolean drawingCacheEnabled = decorView.isDrawingCacheEnabled();
    boolean willNotCacheDrawing = decorView.willNotCacheDrawing();
    decorView.setDrawingCacheEnabled(true);
    decorView.setWillNotCacheDrawing(false);
    Bitmap bmp = decorView.getDrawingCache();
    if (bmp == null) {
        decorView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        decorView.layout(0, 0, decorView.getMeasuredWidth(), decorView.getMeasuredHeight());
        decorView.buildDrawingCache();
        bmp = Bitmap.createBitmap(decorView.getDrawingCache());
    }
    if (bmp == null) return null;
    DisplayMetrics dm = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    Bitmap ret;
    if (isDeleteStatusBar) {
        Resources resources = activity.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int statusBarHeight = resources.getDimensionPixelSize(resourceId);
        ret = Bitmap.createBitmap(
                bmp,
                0,
                statusBarHeight,
                dm.widthPixels,
                dm.heightPixels - statusBarHeight
        );
    } else {
        ret = Bitmap.createBitmap(bmp, 0, 0, dm.widthPixels, dm.heightPixels);
    }
    decorView.destroyDrawingCache();
    decorView.setWillNotCacheDrawing(willNotCacheDrawing);
    decorView.setDrawingCacheEnabled(drawingCacheEnabled);
    return ret;
}
 
Example #27
Source File: PhoneUtil.java    From imsdk-android with MIT License 5 votes vote down vote up
public static int getPhoneWid(Context context) {
    WindowManager windowManager =
        (WindowManager) context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics metric = new DisplayMetrics();
    windowManager.getDefaultDisplay().getMetrics(metric);
    return metric.widthPixels;
}
 
Example #28
Source File: AndroidDrawableMetrics.java    From CrossMobile with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected int finalizeScale(int proposedInterfaceIdiom, Size size) {
    // Get hardware dimensions
    DisplayMetrics displayMetrics = displayMetrics();
    boolean isWide = displayMetrics.widthPixels > displayMetrics.heightPixels;
    int width = isWide ? displayMetrics.heightPixels : displayMetrics.widthPixels;
    int height = isWide ? displayMetrics.widthPixels : displayMetrics.heightPixels;
    setVirtualDimension(isWide ? size.height : size.width, isWide ? size.width : size.height);
    setHardwareDimension(width, height);
    return proposedInterfaceIdiom >= 0
            ? proposedInterfaceIdiom
            : (displayMetrics.heightPixels / displayMetrics.densityDpi) > 6 ? UIUserInterfaceIdiom.Pad : UIUserInterfaceIdiom.Phone;
}
 
Example #29
Source File: ViewUtil.java    From MaterialChipsInput with Apache License 2.0 5 votes vote down vote up
private static int getWindowWidthLandscape(Context context) {
    if(windowWidthLandscape == 0) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        windowWidthLandscape = metrics.widthPixels;
    }

    return windowWidthLandscape;
}
 
Example #30
Source File: ApkTargetMapping.java    From GPT with Apache License 2.0 5 votes vote down vote up
/**
 * getPackage
 *
 * @param parser  android.content.pm.PackageParser
 * @param apkFile APK文件
 * @return PackageParser.Package
 */
private static PackageParser.Package getPackage(android.content.pm.PackageParser parser, File apkFile) {

    DisplayMetrics metrics = new DisplayMetrics();
    metrics.setToDefaults();
    final File sourceFile = new File(apkFile.getAbsolutePath());
    android.content.pm.PackageParser.Package pkg = null;

    // 适配5.0
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
        Method mtd = null;
        try {
            mtd = android.content.pm.PackageParser.class.getDeclaredMethod("parsePackage", File.class,
                    int.class);
        } catch (NoSuchMethodException e1) {
            if (Constants.DEBUG) {
                e1.printStackTrace();
            }

        }

        if (mtd != null) {
            try {
                pkg = parser
                        .parsePackage(apkFile, PackageManager.GET_INTENT_FILTERS | PackageManager.GET_RECEIVERS);
            } catch (PackageParserException e) {
                if (Constants.DEBUG) {
                    e.printStackTrace();
                }
            }
        } else { // L的情况
            pkg = parser.parsePackage(sourceFile, apkFile.getAbsolutePath(), metrics,
                    PackageManager.GET_INTENT_FILTERS | PackageManager.GET_RECEIVERS);
        }
    } else {
        pkg = parser.parsePackage(sourceFile, apkFile.getAbsolutePath(), metrics, PackageManager.GET_INTENT_FILTERS
                | PackageManager.GET_RECEIVERS);
    }
    return pkg;
}