Java Code Examples for android.util.DisplayMetrics

The following examples show how to use android.util.DisplayMetrics. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: WanAndroid   Source File: RotateView.java    License: 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 2
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 3
Source Project: video-player   Source File: ScreenResolution.java    License: 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 4
Source Project: moviedb-android   Source File: CastDetailsBiography.java    License: 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 5
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 6
Source Project: LB-Launcher   Source File: DeviceProfile.java    License: 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 Project: Cotable   Source File: MySwipeRefreshLayout.java    License: 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 8
Source Project: shortyz   Source File: ShortyzActivity.java    License: 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 9
Source Project: Magnet   Source File: RemoveViewTest.java    License: 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 10
Source Project: AdPlayBanner   Source File: PointView.java    License: 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 11
Source Project: leanback-showcase   Source File: ListenerModule.java    License: 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 12
Source Project: holoaccent   Source File: RectDrawable.java    License: Apache License 2.0 5 votes vote down vote up
private Paint initBorderPaint(DisplayMetrics displayMetrics, float borderWidthDp, int borderColor) {
	if (Color.alpha(borderColor) == 0)
		return null;
	if (borderWidthDp <= 0f)
		return null;
	
       float borderWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, borderWidthDp, displayMetrics);
	Paint result = new Paint();
	result.setColor(borderColor);
	result.setStyle(Paint.Style.STROKE);
	result.setStrokeWidth(borderWidth);
	result.setAntiAlias(true);
	return result;
}
 
Example 13
Source Project: commcare-android   Source File: ImageInflationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testScaleUpDueToDensity() {
    // Medium density device with low density target should result in image being scaled up
    // by a factor of 160/120 = 1.33
    int targetDensity = DisplayMetrics.DENSITY_LOW;
    testCorrectInflationWithDensity(targetDensity, mediumDensityDevice, boundingDimens_UNRESTRICTIVE, 133);
}
 
Example 14
Source Project: aptoide-client   Source File: AptoideUtils.java    License: 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 15
Source Project: proofmode   Source File: DeviceInfo.java    License: 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 16
Source Project: springy-heads   Source File: ChatHeadUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Faster than {@link #dpToPx(Context, int)} since metrics is already present.
 * Use this is you are able to cache the reference to display metrics
 * @param metrics
 * @param dp
 * @return
 */
public static int dpToPx(DisplayMetrics metrics, int dp) {
    float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics);
    if (px < 1.0f) {
        px = 1;
    }
    return (int) px;
}
 
Example 17
private int getUsableScreenHeight() {	    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    	DisplayMetrics metrics = new DisplayMetrics();
    	
    	WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(metrics);	 
        
        return metrics.heightPixels;
        
    } else {
    	return rootView.getRootView().getHeight();
    }
}
 
Example 18
Source Project: iBeebo   Source File: Utility.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static int getScreenWidth() {
    Activity activity = BeeboApplication.getInstance().getActivity();
    if (activity != null) {
        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        return metrics.widthPixels;
    }

    return 480;
}
 
Example 19
Source Project: DoraemonKit   Source File: StorageDialogFragment.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onStart() {
    super.onStart();
    Dialog dialog = getDialog();
    if (dialog != null) {
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }
}
 
Example 20
Source Project: ScreenHelper   Source File: ScreenHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static void resetResources(DisplayMetrics activityDm, DisplayMetrics systemDm) {
    //        resources.getDisplayMetrics().xdpi = Resources.getSystem().getDisplayMetrics().density * 72f;
    activityDm.xdpi = systemDm.xdpi;
    activityDm.density = systemDm.density;
    activityDm.scaledDensity = systemDm.scaledDensity; //确保字体的显示大小
    activityDm.densityDpi = systemDm.densityDpi;//确保设置的 dpi
}
 
Example 21
Source Project: Conquer   Source File: BaseActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
    initStatusBar();
    initTheme();
    initLayout();
    userManager = BmobUserManager.getInstance(getApplicationContext());
    manager = BmobChatManager.getInstance(getApplicationContext());
    mApplication = CustomApplication.getInstance();
    currentUser = BmobChatUser.getCurrentUser(context, User.class);
    DisplayMetrics metric = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metric);
    mScreenWidth = metric.widthPixels;
    mScreenHeight = metric.heightPixels;
    loader = ImageLoader.getInstance();

    option_photo = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.default_photo)
            .showImageForEmptyUri(R.drawable.default_photo).showImageOnFail(R.drawable.default_photo)
            .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true)
            .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(200)).build();
    option_pic = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.pic_loading)
            .showImageForEmptyUri(R.drawable.pic_loading).showImageOnFail(R.drawable.pic_loading)
            .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true)
            .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(200)).build();
    dbUtils = DbUtils.create(context);
}
 
Example 22
Source Project: Matisse   Source File: SizeUtils.java    License: 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 23
Source Project: echo   Source File: RingView.java    License: 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 24
Source Project: earth   Source File: LegacyEarthSharedState.java    License: 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 25
Source Project: coursera-android   Source File: BubbleActivity.java    License: 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 26
private int getScreenHeight()
{
    WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics outMetrics = new DisplayMetrics();
    wm.getDefaultDisplay().getMetrics(outMetrics);
    return outMetrics.heightPixels;
}
 
Example 27
Source Project: react-native-android-vitamio   Source File: Device.java    License: 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 28
Source Project: imsdk-android   Source File: UnreadMsgUtils.java    License: 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 29
Source Project: floatingsearchview   Source File: Util.java    License: 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 30
Source Project: MaterialChipsInput   Source File: ViewUtil.java    License: 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;
}