android.R.id.content 是什么,有什么用

前言

最近看代码看到了 android.R.id.content

  manager.beginTransaction()
                    .add(android.R.id.content, this, FilterFragment.class.getName())
                    .commitAllowingStateLoss();

android.R.id.content 是个什么布局,点进去看


image.png

一.android.R.id.content

android.R.id.content 提供了视图的根元素,是一个FrameLayout,只有一个子元素,就是平时在onCreate方法中设置的setContentView。也即,当我们在Layout文件中设置一个布局文件时,实际上该布局被一个FrameLayout所包含。

需要注意的是,在不同的SDK版本下,该FrameLayout所指的显示区域也不同。具体如下

在sdk 14+(native ActionBar),该显示区域指的是ActionBar下面的部分

在Support Library revision lower than 19,使用AppCompat,则显示区域包含ActionBar

在Support Library revision 19 (or greater),使用AppCompat,则显示区域不包含ActionBar,即行为与第一种情况相同。

所以如果不使用Support Library或使用Support Library的最新版本,则R.id.content所指的区域都是ActionBar以下

二.R.id.content 巧妙用途

1.获取导航栏高度

android.R.id.content 一般不包含导航栏的高度,所以我们可以用它获取导航栏的高度。

int contentTop = findViewById(android.R.id.content).getTop();  
//statusBarHeight是上面所求的状态栏的高度  
int titleBarHeight = contentTop - statusBarHeight;

2.获取键盘高度

1、键盘没打开时获取android.R.id.content的可见区域高度height1,
2、键盘打开时再获取android.R.id.content的可见区域高度height2,
3、键盘的高度height1-height2

   private View globalView;
    private int firstHeight;
    private boolean isFirst = true;

    globalView = findViewById(android.R.id.content);
    globalView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Rect rect = new Rect();
            globalView.getWindowVisibleDisplayFrame(rect);
            if (isFirst) {
                isFirst = false;
                firstHeight = rect.height();
            } else {
                int height = rect.height();
                if (height < firstHeight) {
                    System.out.println("键盘打开 " + (firstHeight - height));
                } else {
                    System.out.println("键盘关闭 ");
                }
            }
        }
    });
--------------------- 

3.那怎么获取状态栏的高度

getDecorView的getWindowVisibleDisplayFrame方法可以获取程序显示的区域,包括标题栏,但不包括状态栏,所以就可以通过距离top算出状态栏的高度了。

Rect frame = new Rect();  
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
int statusBarHeight = frame.top;

你可能感兴趣的:(android.R.id.content 是什么,有什么用)