What is the correct way to specify dimensions in DIP from Java code?

前端 未结 4 1266
Happy的楠姐
Happy的楠姐 2020-11-28 01:45

I found that it is possible to set dimensions of my interface elements in XML layouts using DIPs as in following fragment:

android:layout_width=\"10dip\"
         


        
4条回答
  •  春和景丽
    2020-11-28 02:30

    I think the best way is not to define any dimensions in code, but use the values/dimens.xml file instead. You can always define your dimension in the desired unit like:

    120dp
    

    and then refer to this in your Activity like:

    getResources().getDimensions(R.dimen.my_layout_height);
    

    This would return pixels after doing the necessary conversions. And also of course you can refer to this in your other XMLs like:

    android:layout_width="@dimen/my_layout_height"
    

提交回复
热议问题