首页 \ 问答 \ 使用软导航栏正确检测屏幕尺寸(Detecting screensize correctly with soft navigation bar)

使用软导航栏正确检测屏幕尺寸(Detecting screensize correctly with soft navigation bar)

我正在使用Xamarin在C#中开发一个应用程序。 我使用以下代码来检测设备屏幕大小:

var metrics = Resources.DisplayMetrics;
int widthInDp = metrics.WidthPixels / Resources.DisplayMetrics.Density;
int heightInDp = metrics.HeightPixels / Resources.DisplayMetrics.Density;

在具有物理导航按钮且没有软导航栏的设备(Samsung SM-E7000)上,此方法返回预期结果:

360dp x 640dp in portrait mode
640dp x 360dp in landscape mode

但是,在没有物理导航按钮但具有软导航栏(Nexus 4)的设备上,此方法会返回意外(对我而言)结果:

384dp x 592dp in portrait mode
598dp x 384dp in landscape mode

对于Nexus来说,结果在纵向模式下允许48dp用于软导航栏,在横向模式下允许42dp。

我想使用全屏 - 如果设备有一个软导航栏我想隐藏它并使用空间。 我可以隐藏软导航栏,但我需要能够检测实际的屏幕尺寸(例如Nexus 4的384dp x 640dp),或者设备是否有软导航栏(最好是它的大小),所以我可以调整隐藏时可用的额外空间。

我已经看到几个针对Java的stackoverflow问题,其代码类似于:

public boolean hasNavBar (Resources resources)
{
    int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
    return id > 0 && resources.getBoolean(id);
}

但我找不到C#/ Xamarin的等价物。

任何帮助赞赏。


I am developing an app in C# using Xamarin. I use the following code to detect the device screensize:

var metrics = Resources.DisplayMetrics;
int widthInDp = metrics.WidthPixels / Resources.DisplayMetrics.Density;
int heightInDp = metrics.HeightPixels / Resources.DisplayMetrics.Density;

On a device that has physical navigation buttons, and no soft navigation bar, (Samsung SM-E7000), this method returns expected results:

360dp x 640dp in portrait mode
640dp x 360dp in landscape mode

However, on a device that does not have physical navigation buttons, but has the soft navigation bar, (Nexus 4), this method returns unexpected (to me) results:

384dp x 592dp in portrait mode
598dp x 384dp in landscape mode

It seems for the Nexus the results allow 48dp for the soft navigation bar in portrait mode, and 42dp in landscape mode.

I want to use the fullscreen - if the device has a soft navigation bar I want to hide it and use the space. I can hide the soft navigation bar, but I need to be able to detect either the actual screen size (e.g. 384dp x 640dp for the Nexus 4), or whether the device has a soft navigation bar (and preferably its size), so I can adjust for the extra space available when it is hidden.

I have seen several stackoverflow questions answered for Java with code similar to:

public boolean hasNavBar (Resources resources)
{
    int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
    return id > 0 && resources.getBoolean(id);
}

but I can't find the C#/Xamarin equivalent.

Any help appreciated.


原文:https://stackoverflow.com/questions/39096192
更新时间:2024-05-02 14:05

最满意答案

错误是告诉你到底发生了什么问题; 你用太多的参数调用构造函数。 为了明白我的意思,请看看在makeRecord的默认实现中通常如何构建日志记录:

def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
    """
    A factory method which can be overridden in subclasses to create
    specialized LogRecords.
    """
    rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func)
    if extra is not None:
        for key in extra:
            if (key in ["message", "asctime"]) or (key in rv.__dict__):
                raise KeyError("Attempt to overwrite %r in LogRecord" % key)
            rv.__dict__[key] = extra[key]
    return rv

请注意makeRecord如何使用一个extra参数,它不直接传递给LogRecord ? 另一方面,你直接将它传递给LogRecord.__init__ ,这会导致错误。

从这里,你有两个选择; 您可以提供更完整的makeRecord实现,或者您可以尝试使用LoggerAdapter类,它应该可以帮助您用较少的代码实现相同的目标。

这是一个例子:

# Common log info to be added to all logs reported with `log_adapter`
context = {'host': 'localhost'}

log = logging.getLogger('testing')
log.addHandler(logging.StreamHandler())
d = {'host': '192.168.0.1'}

log_adapter = logging.LoggerAdapter(log, context)
log_adapter.warning('Hi', d)

如果您需要在每次记录日志时计算“主机”的值(例如),则可以使context成为类似字典的类的实例。 像这样:

class LogContext(object):

    def __getitem__(self, key):
        if key == 'host':
            return 'localhost'
        raise KeyError(key)

    def __iter__(self):
        return iter(['host'])

log_adapter = logging.LoggerAdapter(log, LogContext())
log_adapter.warning('Hi', d)

有一点需要注意LoggingAdapter ,它显然没有将所有便捷的快捷函数定义为普通的Logger类。 这就是为什么我已经调用了warning方法,而不是像上面那样warn

有关LoggingAdapter和添加上下文到日志的更多信息可以在python文档中找到。

注 - 我的示例中没有包含MyLogHandlerMyLogFormatterMongoLogger ,因为它们与问题/错误无关。


The error is telling you exactly what's wrong; you are calling the constructor with too many arguments. To see what I mean, take a look at how log-records are ordinarily constructed in the default implementation of makeRecord:

def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
    """
    A factory method which can be overridden in subclasses to create
    specialized LogRecords.
    """
    rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func)
    if extra is not None:
        for key in extra:
            if (key in ["message", "asctime"]) or (key in rv.__dict__):
                raise KeyError("Attempt to overwrite %r in LogRecord" % key)
            rv.__dict__[key] = extra[key]
    return rv

Notice how makeRecord takes an extra param that it doesn't pass directly to LogRecord? You, on the other hand, are passing that directly to LogRecord.__init__, which is causing the error.

From here, you've got two options; you could provide a more complete implementation of makeRecord, or you could try using the LoggerAdapter class which should help you achieve the same goal with less code.

Here's an example:

# Common log info to be added to all logs reported with `log_adapter`
context = {'host': 'localhost'}

log = logging.getLogger('testing')
log.addHandler(logging.StreamHandler())
d = {'host': '192.168.0.1'}

log_adapter = logging.LoggerAdapter(log, context)
log_adapter.warning('Hi', d)

If you need to calculate the value of 'host' (for example) each time something is logged, you could make context an instance of a class that looks like a dictionary. Like so:

class LogContext(object):

    def __getitem__(self, key):
        if key == 'host':
            return 'localhost'
        raise KeyError(key)

    def __iter__(self):
        return iter(['host'])

log_adapter = logging.LoggerAdapter(log, LogContext())
log_adapter.warning('Hi', d)

One thing to note about LoggingAdapter, it apparently doesn't define all of the handy shortcut functions as the ordinary Logger class. That's why I've called the warning method instead of warn as you did above.

More info on LoggingAdapter and adding context to your logs can be found in the python docs.

NOTE - I didn't include MyLogHandler, MyLogFormatter, or MongoLogger in my examples as they were not relevant to the issue/error.

相关问答

更多

相关文章

更多

最新问答

更多
  • sp_updatestats是否导致SQL Server 2005中无法访问表?(Does sp_updatestats cause tables to be inaccessible in SQL Server 2005?)
  • 如何创建一个可以与持续运行的服务交互的CLI,类似于MySQL的shell?(How to create a CLI that can interact with a continuously running service, similar to MySQL's shell?)
  • AESGCM解密失败的MAC(AESGCM decryption failing with MAC)
  • Zurb Foundation 4 - 嵌套网格对齐问题(Zurb Foundation 4 - Nested grid alignment issues)
  • 湖北京山哪里有修平板计算机的
  • SimplePie问题(SimplePie Problem)
  • 在不同的任务中,我们可以同时使用多少“上下文”?(How many 'context' we can use at a time simultaneously in different tasks?)
  • HTML / Javascript:从子目录启用文件夹访问(HTML/Javascript: Enabling folder access from a subdirectory)
  • 为什么我会收到链接错误?(Why do I get a linker error?)
  • 如何正确定义析构函数(How to properly define destructor)
  • 垂直切换菜单打开第3级父级。(Vertical toggle menu 3rd level parent stay opened. jQuery)
  • 类型不匹配 - JavaScript(Type mismatch - JavaScript)
  • 为什么当我将模型传递给我的.Net MVC 4控制器操作时,它坚持在部分更新中使用它?(Why is it that when I pass a Model to my .Net MVC 4 Controller Action it insists on using it in the Partial Update?)
  • 在使用熊猫和statsmodels时拉取变量名称(Pulling variable names when using pandas and statsmodels)
  • 如何开启mysql计划事件
  • 检查数组的总和是否大于最大数,反之亦然javascript(checking if sum of array is greater than max number and vice versa javascript)
  • 使用OpenGL ES绘制轮廓(Drawing Outline with OpenGL ES)
  • java日历格式(java Calendar format)
  • Python PANDAS:将pandas / numpy转换为dask数据框/数组(Python PANDAS: Converting from pandas/numpy to dask dataframe/array)
  • 如何搜索附加在elasticsearch索引中的文档的内容(How to search a content of a document attached in elasticsearch index)
  • LinQ to Entities:做相反的查询(LinQ to Entities: Doing the opposite query)
  • 从ExtJs 4.1商店中删除记录时会触发哪些事件(Which events get fired when a record is removed from ExtJs 4.1 store)
  • 运行javascript后如何截取网页截图[关闭](How to take screenshot of a webpage after running javascript [closed])
  • 如何使用GlassFish打印完整的堆栈跟踪?(How can I print the full stack trace with GlassFish?)
  • 如何获取某个exe应用程序的出站HTTP请求?(how to get the outbound HTTP request of a certain exe application?)
  • 嗨,Android重叠背景片段和膨胀异常(Hi, Android overlapping background fragment and inflate exception)
  • Assimp详细说明typedef(Assimp elaborated type refers to typedef)
  • 初始化继承类中不同对象的列表(initialize list of different objects in inherited class)
  • 使用jquery ajax在gridview行中保存星级评分(Save star rating in a gridview row using jquery ajax)
  • Geoxml3 groundOverlay zIndex(Geoxml3 groundOverlay zIndex)