Setting fixed width size of view with pt/mm/in ANDROID

妖精的绣舞 提交于 2019-12-11 02:28:28

问题


I'm trying to set fix width to a view. “in”, “mm”, and “pt” are density independent and the same size on every device or i am wrong? My view width should be 141.3pt/49.8mm , so i am setting in the XML android:layout_width="141.3pt" or via code:

float requiredPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, (float) 141.3, dm);
ViewGroup.LayoutParams params = mRequiredSizeLine.getLayoutParams();
        params.width = (int)requiredPx;
        mRequiredSizeLine.setLayoutParams(params);

The thing is that, this is ok on some devices(on most of them) but for example on Samsung Galaxy Stratosphere 2 it is not ok. Also i have a method that calculate screen display width in in and mm

private double checkDeviceWidthInInches(){
    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    double x = Math.pow(dm.widthPixels/dm.xdpi,2);
    double y = Math.pow(dm.heightPixels/dm.ydpi,2);

    return Math.sqrt(x);

and you can notice from the first image below, this is also incorrect(it is not possible the screen width to be 76 mm) .

Image of Samsung Galaxy Stratosphere 2(THIS IS INCORRECT) and Image of Samsung Galaxy S4(THIS IS CORRECT)

So what do you think? Could be some problem with the device or ? Link for device spec http://www.samsung.com/us/mobile/cell-phones/SCH-I415SAAVZW

Any suggestion? Thanks


回答1:


You should always specify dimensions of your views in dp (density-independent pixels). Avoid using other units. When you want to specify a size of text use sp units. Difference between px, dp, dip and sp in Android



来源:https://stackoverflow.com/questions/27339222/setting-fixed-width-size-of-view-with-pt-mm-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!