user6586336
user6586336

Reputation: 41

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. 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). The test cases should fail of someone changes the unit of text from dp to px or any other unit.

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

Thanks in advance!

Upvotes: 4

Views: 252

Answers (2)

Eugen Martynov
Eugen Martynov

Reputation: 20130

There is already lint check that you don't use dp as the dimension for text sizes. 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. 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.

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

Upvotes: 1

Gabe Sechan
Gabe Sechan

Reputation: 93561

First off, never do textSize in dp. They should always use sp so people with sight issues can scale it up as needed.

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? Don't, that's google's job to test when they test the framework. 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.

Upvotes: 3

Related Questions