Android开发中获取尺寸(View和屏幕分辨率)

摘要

  • 在Android开发中有时需要获取View的尺寸,踩过的无数坑就是在onCreate()方法中获取,无论是getWidth()还是getMeasuredWidth()获取到的都是0,为什么呢?因为此时View尚未绘制完成,那就在onResume()方法中获取吧,结果仍然获取不到。
  • 有时为了适配还需要获取屏幕的分辨率,一起来吧。

获取View尺寸正确姿势

  • 正确姿势(1)
        final TextView tv_main_activity = (TextView) findViewById(R.id.tv_main_activity);

        ViewTreeObserver vto = tv_main_activity.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                tv_main_activity.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int width = tv_main_activity.getWidth();
                Log.e("MainActivity", "width=" + width);
            }
        });
  • 正确姿势(2)
        final TextView tv_main_activity = (TextView) findViewById(R.id.tv_main_activity);

        ViewTreeObserver vto = tv_main_activity.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                tv_main_activity.getViewTreeObserver().removeOnPreDrawListener(this);
                int width = tv_main_activity.getWidth();
                Log.e("MainActivity", "width=" + width);
                return false;
            }
        });
  • 正确姿势(3):
        final TextView tv_main_activity = (TextView) findViewById(R.id.tv_main_activity);

        tv_main_activity.post(new Runnable() {
            @Override
            public void run() {
                int width = tv_main_activity.getWidth();
                Log.e("MainActivity", "width=" + width);
            }
        });

获取屏幕分辨率

  • 在Activity中获取
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int widthPixels = dm.widthPixels;
        Log.e("MainActivity", "widthPixels=" + widthPixels);
  • 在application中获取
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        int widthPixels = dm.widthPixels;
        Log.e("MainActivity", "widthPixels=" + widthPixels);

你可能感兴趣的:(Android基础知识)