简体   繁体   English

如何确定Java中View的像素单位(px,dp等)?

[英]How to determine the Pixel Unit (px, dp, etc) of a View in Java?

I am trying to write a unit test to verify that DIPs are used. 我正在尝试编写单元测试来验证是否使用了DIP。 I am able to read the size value with editText.getTextSize() but I am unable to read unit of text (in this case it's to ensure "dp" usage). 我能够使用editText.getTextSize()读取大小值,但我无法读取文本单元(在这种情况下,它是为了确保“dp”用法)。 The test cases should fail of someone changes the unit of text from dp to px or any other unit. 如果某人将文本单位从dp更改为px或任何其他单位,则测试用例将失败。

<EditText
    android:id="@+id/someId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="48dp"/>

Thanks in advance! 提前致谢!

First off, never do textSize in dp . 首先,永远不要在dp执行textSize。 They should always use sp so people with sight issues can scale it up as needed. 他们应该总是使用sp因此有视力问题的人可以根据需要进行扩展。

Secondly, why would you write a unit test for this? 其次,为什么要为此编写单元测试? What are you testing? 你在测试什么? That if you put a given size in xml that its actually used? 如果你把一个给定的大小放在它实际使用的xml中? Don't, that's google's job to test when they test the framework. 不,这是google在测试框架时要测试的工作。 Writing a unit test to do that is an utter waste of time, as it will never break. 编写一个单元测试就可以完全浪费时间,因为它永远不会破坏。 Are you testing that a certain element is a certain size? 您是否测试某个元素是否具有特定大小? Then test that, you wouldn't test if its specified in dp vs px . 然后测试一下,你不会测试它是否在dp vs px指定。

There is already lint check that you don't use dp as the dimension for text sizes. 已经有lint检查您不使用dp作为文本大小的维度。 It produces a warning, so it doesn't break the build. 它会产生警告,因此不会破坏构建。 But you can make it strict to fail: 但你可以严格要求失败:

lintOptions {
        warningsAsErrors true
        abortOnError true // Fail early.
}

The @Gabe's answer has a good point that you test the side effect through Android framework. @ Gabe的答案很好,你可以通过Android框架测试副作用。 If you really want to guard that sizes for the specific element is special value with special dimensions then add test/lint check for xml itself. 如果你真的想要保护特定元素的大小是具有特殊尺寸的特殊值,那么为xml本身添加test / lint检查。

As for me, it doesn't have much value - it doesn't break functionality, it adds complexity with consistency and support, it adds time for running tests. 至于我,它没有多大价值 - 它不会破坏功能,它增加了一致性和支持的复杂性,它增加了运行测试的时间。 As well you will notice it through your regression test or, in worth case, users will complain about it. 您也会通过回归测试注意到它,或者在值得的情况下,用户会抱怨它。

One suggestion - look to styles and theming, don't copy paste text sizes and other view attributes 一个建议 - 查看样式和主题,不要复制粘贴文本大小和其他视图属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM