简体   繁体   中英

Inconsistency between px and dp in android

OK, so here's a wobbly one... Before asking my question, I'll point out that I have read this: What is the difference between "px", "dp", "dip" and "sp" on Android? So here's my problem, I have some squares on screen (EditText) which I define in my XML using dp units, and identifying them square1, square2 etc., and they are positioned in a FrameLayout (since absolute layout is deprecated and that I don't see any other layout that would suit my purposes; I want to control the position of the squares on screen by programming, soI use

square1.setX(cc1x); 
square1.setY(cc1y);
square2.setX(cc2x); 
square2.setY(cc2y);

and so on, and where cc1x, cc1y, cc2x, cc2y are int variables that change according to the logic of the app. The problem is that the java syntax doesn't allow adding a unit to this integer value of the variables, so on some screens my app works just perfectly, but on screens with a different density, everything is either too far apart, either overlapping...

And finally the question(s): Is there a way of "forcing" the units into the setX / setY statements?

or

Is there a way to get the density of the screen of the device where my app will run? (in which case I could recalculate the X/Y coordinates accordingly) (I didn't do research on this second possibility yet, as I just thought of it whilst writing this, so please accept my apologies if it is a duplicate of some other question). Thanks in advance for your thoughts.

You can add this method to easily convert between DP on the screen and PX of the device

 public static float convertDpToPx(Context context, int dp) {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
}

I wanted to update on this thread, since I've found a far better solution to the problem, though the answers you guys (& girls?) really did teach me a lot, for which my gratitude. Finally, njzk2's answer has made me reconsider the whole approach to what I wanted to do. So, instead of moving my boxes around, which resulted in the dimensioning problems, now I just move the content of the boxes around, leaving the boxes nicely positioned in place, which is by far more easy. Anyway, I hope this will result usefull to other starters like me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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