Android How to add a custom xml file in res/values and how to register the customvalues.xml with the system

后端 未结 3 592
我在风中等你
我在风中等你 2020-12-10 10:53

I want to add a custom xml which having URLs to the res/values folder. I can add the file but how to read its content by getResources() ?

相关标签:
3条回答
  • 2020-12-10 11:36

    Yes you can have a custom file: I just did this a couple of times. 1) Make a new xml file. 2) Use file format as as wrapper for yours Example:

    <?xml version="1.0" encoding="utf-8" ?>
    <resources>
        <item name="languages">
            <languages>
                <language>
                    <isocode>
                        en-UK
                    </isocode>
                    <name>
                        English (UK)
                    </name>
                </language>
            </languages>
        </item>
    </resources>
    
    0 讨论(0)
  • 2020-12-10 11:37

    Update: This doesn't seem to work anymore (but it used to) and you cannot create your own custom types in android. Only the standard available resource types work now.

    Therefore, the only way to achieve something like this would be, have your separate file as suggested, url.xml and have all yours URLs in that file so that it doesn't get mixed up with the other Strings. It just improves readability and maintainability, AFAIK.

    The URL item now looks like,

    <item name="myUrl" type="string">http://myUrl.com</item>
    

    And you needs to be accessed the usual way:

    String myurl = getResources().getString(R.string.myUrl);
    

    Original Answer:

    Try something like this:-

    url.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <item name="myUrl" type="urls">http://myUrl.com</item>
    </resources>
    

    And in your activity, get it like this:-

    String s = getResources().getString(R.urls.myUrl);
    

    Note:- You needn't register your xml anywhere. Just make sure its available in res/values folder.

    Snapshot:-

    How I used

    0 讨论(0)
  • 2020-12-10 11:38
    1. Create your custom xml file, ensure it is in res folder (I've tested this by putting it in res/values folder)
    2. Ensure all the values you place in this XML are of a standard type.
    3. You can then use the corresponding R call. For example for integer you do R.integer.YOUR_CUSTOM_XML_VALUE. Doesn't matter which xml this integer is located in, it will be registered by R as long as it is in res folder.
    0 讨论(0)
提交回复
热议问题