Device TabGroup的Tab高度(以像素为单位)取决于设备屏幕大小

时间:2013-02-04 11:16:05

标签: android height pixel

我需要在我的应用中以像素为单位获得标签的高度(如图所示)。 我需要一些信息来帮助我了解屏幕大小所依赖的Tab高度。任何人都可以帮助我吗?

提前致谢enter image description here

说实话我在代码中不需要Tab的大小,我认为每个具有相同大小的设备都会有相同的Tab高度,所以我想知道屏幕的哪个部分会占用我的Tab,

e.g。我有1080 X 720像素的设备,我的Tab会占用1/10的部分,这意味着Tab的高度将是108像素

1 个答案:

答案 0 :(得分:0)

我之前在评论中的意思是,这里有许多流行的解决方案来获取任何android视图的高度和宽度。 我现在已经测试了这个代码,它运行正常。试试这个:

final RelativeLayout topLayout  = (RelativeLayout) findViewById(R.id.topRelLayout);
        ViewTreeObserver viewTreeObserver = topLayout.getViewTreeObserver();
        if (viewTreeObserver.isAlive()) {
          viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if(Integer.valueOf(android.os.Build.VERSION.SDK_INT) >= 16)
                topLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                else
                topLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
             int  viewWidth = tabs.getWidth();
              int viewHeight = tabs.getHeight();

              Toast.makeText(HomeScreenActivity.this, "height = "  + viewHeight + " width = " + viewWidth , 2000).show();
            }
          });
        }

其中topRelLayout是xml文件的根布局的id,而tabs是对标签视图的引用。

即使遵循简单的代码也能正常工作。

tabs.post(new Runnable() {
            @Override
            public void run() {
                int w = tabs.getMeasuredWidth();
                int h = tabs.getMeasuredHeight();
                Toast.makeText(HomeScreenActivity.this, "height = "  + h + " width = " + w , 2000).show();
            }
        });

使用任一解决方案,您都可以获得任何屏幕尺寸的任何视图的高度/宽度。

编辑:

在阅读您编辑过的问题后,我假设您需要Tab小部件占用屏幕的百分比。 只有我知道的解决方案才能实现:

WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
         final   Display display = wm.getDefaultDisplay();

            tabs.post(new Runnable() {
                @Override
                public void run() {
                    int h = tabs.getMeasuredHeight();
                    int screenHeight = 0;
                    if(Integer.valueOf(android.os.Build.VERSION.SDK_INT) >= 13)
                    {
                        Point point = new Point();
                     display.getSize(point);
                     screenHeight = point.y;
                    }
                    else
                        screenHeight = display.getHeight();
                    double tabPart = (((double)h/(double)screenHeight) * 100); 
                    Toast.makeText(HomeScreenActivity.this, "height = "  + screenHeight + " tabPart = " + tabPart  + " %", 2000).show();


                }
            });