what is ids.xml used for?

后端 未结 5 510
予麋鹿
予麋鹿 2020-12-13 23:40

Just a quick question, what is the ids.xml used for when developing an Android app? I saw an example on the android resources webpage which contained:



        
相关标签:
5条回答
  • 2020-12-13 23:50

    id.xml is generally used to declare the id's that you use for the views in the layouts.

    you could use something like

    <TextView android:id="@id/snack">
    

    for your given xml.

    0 讨论(0)
  • 2020-12-13 23:51

    ids.xml has the following advantage: all ids were declared, so compiler can recognize them. If something like this:

    <TextView
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignBelow="@id/text2"
        android:text="...."/>
    <TextView
        android:id="@+id/text2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="...."/>
    

    Can result in compiling error because text2 was refered before declared

    0 讨论(0)
  • 2020-12-14 00:00

    Another application for id.xml is in respect to layouts and library projects. Let's say you specify a generic list of options in a library (dialog) layout

    <CheckedTextView android:id="@+id/checked_option_one"...
    <CheckedTextView android:id="@+id/checked_option_two"...
    ...
    

    and handle these views in a generic (dialog) fragment

    optionOneCheck = (CheckedTextView)rootView.findViewById(R.id.checked_option_one);
    optionTwoCheck = (CheckedTextView)rootView.findViewById(R.id.checked_option_two);
    

    If you remove any of the view declarations from a copy of the layout in a main project, you will get a "no such field" error exception at runtime.

    The compiler doesn't complain, but at runtime the id isn't actually there/known.

    Declaring the ids in id.xml and using

    <CheckedTextView android:id="@id/checked_option_one"...
    ...
    

    avoids the runtime error

    0 讨论(0)
  • 2020-12-14 00:08

    When creating views dynamically, predefining id's in ids.xml gives the posibility to reference a newly created view. After you use the setId(id) method you can access the view as if it had been defined in XML. This blog post has a nice example.

    0 讨论(0)
  • 2020-12-14 00:10

    ids.xml is much more powerful. You can predefine values like

    <item name="fragment_my_feature" type="layout"/>
    <item name="my_project_red" type="color"/>
    

    not only id. Actually you can use more resource types: https://developer.android.com/guide/topics/resources/more-resources

    It's extremely helpful to predefine some layouts, colors etc. in root module for multi-module app. You can keep actual layouts, colors, etc. in specific app module which has root module as dependency.

    0 讨论(0)
提交回复
热议问题