在API级别30Android 11上获取屏幕宽度:不建议使用getDefaultDisplay和getMetrics我们应该用什么代替呢? 您可以使用

问题描述

我目前这样计算屏幕宽度:

public static int getScreenWidth(@NonNull Context context) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    return displayMetrics.widthPixels;
}

由于这两个函数( getDefaultDisplay() getMetrics())现在已被弃用,我们应该使用什么呢?

解决方法

要计算减去任何系统栏的屏幕宽度,这应该起作用:

<label for="">Headline</label>
<select name="google_fonts_headline" id="font-selection">
    <option value="">Please Select</option>
</select>
<br/>
<br/>

<label for="">Font Style</label>
<select name="google_fonts_style" id="style-selection">
    <option value="">Please Select</option>
</select>

   <label for="">Subline</label>
<select name="google_fonts_subline" class="fonts" id="subline-selection">
    <option valuue="">Please Select</option>
</select>

   <div class="preview" style='border:1px solid red;'>
    <h1>headline test</h1>
    <p>subline here.</p>
</div>

<script>

    $(document).ready(function(){
        function getArray(){
            return $.getJSON('https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyD5e27MJ3ujq0cjs720_rElG5tAf3KbPb8');
        }

        getArray().done(function(fonts) {  
            var str = '';
            var subset = '';

            $.each(fonts,function(k,v) {
                // font family
                $.each(fonts.items,function(key,val) {
                    str+= '<option value='+ val.family +'>' + val.family + '</option>';

                    // // font style
                    $.each(val.variants,function(i,ctg){
                        subset+= '<option value='+ ctg +'>' + ctg + '</option>';
                    })
                })
            })

            $('#font-selection').append(str);
            $('#subline-selection').append(str);
            $('#style-selection').append(subset);
        });


        // font selection 
        function fontSelection(){
            $("select.fonts").change(function (e){
                var id =$('#font-selection option' +':selected').val();  
                var id2 =$('#subline-selection option' +':selected').val();  

                $(".preview h1").css('font-family',id);
                $(".preview p").css('font-family',id2);

                var font = $('#font-selection').val(),font2 = $('#subline-selection').val(),name = this.options[this.selectedIndex].textContent;
                
               
                if (font === 'default') {
                    $(this).css("font-family",'inherit');
                } else {
                    $(this).css("font-family",name);
                    var link = replacestyle('https://fonts.googleapis.com/css?family=' + font +  "|" + font2);
                }
            });
        }

        fontSelection();


        // font style
        function styleSelection(){
            $("#font-selection").change(function(e){
                $('#style-selection').css('border','1px solid red');
            })
        }

        styleSelection();
    })

    // append to <head>
    function replacestyle(url) {
        if (!document.getElementById('style_fonts')) {
            var style_tag = document.createElement('link');
            style_tag.rel = 'stylesheet';
            style_tag.id = 'style_fonts';
            style_tag.type = 'text/css';
            document.getElementsByTagName('head')[0].appendChild(style_tag);
            replacestyle(url);
        }
        document.getElementById('style_fonts').href = url;
    }

    // append to <script>
    var script = document.createElement('script');
    script.src = 'https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyD5e27MJ3ujq0cjs720_rElG5tAf3KbPb8';
    document.body.appendChild(script);
</script>

请注意,这不完全相同:用高度测试此结果会产生不同的结果,而且我无法用新API复制旧API的功能(部分原因是旧API的行为有点难以解释,而并非总是您想要的,因此已弃用)。不过,实际上,作为通用屏幕宽度,它在很多方面都应该足够好。

,
@RequiresApi(20)
inline val Fragment.windowHeight: Int
    get() {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val metrics = requireActivity().windowManager.currentWindowMetrics
            val insets = metrics.windowInsets.getInsets(WindowInsets.Type.systemBars())
            metrics.bounds.height() - insets.bottom - insets.top
        } else {
            val view = requireActivity().window.decorView
            val insets = WindowInsetsCompat.toWindowInsetsCompat(view.rootWindowInsets,view).getInsets(WindowInsetsCompat.Type.systemBars())
            resources.displayMetrics.heightPixels - insets.bottom - insets.top
        }
    }

@RequiresApi(20)
inline val Fragment.windowWidth: Int
    get() {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val metrics = requireActivity().windowManager.currentWindowMetrics
            val insets = metrics.windowInsets.getInsets(WindowInsets.Type.systemBars())
            metrics.bounds.width() - insets.left - insets.right
        } else {
            val view = requireActivity().window.decorView
            val insets = WindowInsetsCompat.toWindowInsetsCompat(view.rootWindowInsets,view).getInsets(WindowInsetsCompat.Type.systemBars())
            resources.displayMetrics.widthPixels - insets.left - insets.right
        }
    }

这需要 androidx.core 版本 1.5.x

,

您可以使用

Context.getDisplay()而不是getDefaultDisplay()

display.getRealMatrix(displayMetrics)而不是display.getMetrics(displayMetrics)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...