I have two different layouts for two different Activities. There is a button in each of these layouts with the same id: "@+id/btnOK". When I set a property for one of these buttons programmatically, I get a NullPointerException
. But when I change one of ids, everything is okay.
Is it really true that we cannot have duplicate IDs in different layouts in android?
You can have the same IDs but it should be in different layouts. The same layout cannot handle duplicate IDs. I have taken two layouts as you did containing buttons having as "btn". I am calling the Activity2 having newxml.xml from the Activity1 having main.xml.
Here is my code:
main.xml:
Activity1:
newxml:
Activity2:
I resolved the problem but I did not find the reason. In my manifest file, one of activities had the "android:label="@string/app_name". I removed it and set it for my main activity.
Previous manifest:
New manifest:
Does anybody know the reason?
I imagine there would be an issue in the
R.java
class, as this class will have public static members corresponding to eachView
id.For it to work, the
R.java
class would need to rename some of those id's, and then how would you find them?To me it looks all right (and sometimes quite natural) to use duplicate ids, as long as you do it correctly: instead of
Activity.findViewById()
which always returns the first matching view, useViewGroup.findViewById()
(ViewGroup
can beLinearLayout
,FrameLayout
etc) which returns view withing the view group.To avoid lint warnings:
(Preferred) Place content of the ViewGroup in separate layout XML and use
This way you can have several includes of same layout with different parent ids (but same child ids) and lint will never complain.
Disable Lint warning for the project by unticking the box "Duplicate ids within a single layout" in
*Settings/Editor/Inspections*
On the "Duplicate Ids in layouts" topic, extracted from android developers
Defining IDs for view objects is important when creating a RelativeLayout. In a relative layout, sibling views can define their layout relative to another sibling view, which is referenced by the unique ID.
An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching (which may often be the entire tree, so it's best to be completely unique when possible).
Which means different layouts may declare identical IDs, tho it's not a best practice.