Accessing integer resources in xml

前端 未结 6 1459
醉酒成梦
醉酒成梦 2021-02-02 08:23

I have read this where found that how to access integer resources in java class but no docs for another resource.

Here is Resources at res/values/integers.xml

         


        
6条回答
  •  梦谈多话
    2021-02-02 08:50

    The accepted answer is completely mis-guiding. Unless there is a specific unique reason, you should never use an Integer resource for setting padding sizes. Not only in XML but also in code. This is why you experienced an UnsupportedOperationException. Integer resources are not scaled based on the DPI of screens. Which means you will not get consistently spaced padding for all devices. Dimen resources will automatically adjust their value for you. Your java code should look like this:

    EditText mUsername = (EditText) this.findViewById(R.id.user_name);
    int padding = (int) this.getResources().getDimension(R.dimen.input_field_padding);
    mUsername.setPadding(padding, padding, padding, padding);
    

    Which, btw, there's no need to set the padding of the EditText element in code if you already set it in the XML. Unless you wanted to change it to a different value at run time.

    Read more here:
    Density Independence
    Working with XML Layouts

提交回复
热议问题