Can i have 2 different views with same id in android

回眸只為那壹抹淺笑 提交于 2019-12-20 05:26:26

问题


Is it right to have same Id for a TextView and a ImageView ? Since they belong to one entity I gave both of them same Id. If yes.. then how can I find these views by id separately ?


回答1:


Is it right to have same Id for a TextView and a ImageView ?

Short Answer: NO

Long Answer: It is not right to use same IDs because by doing it can cause runtime errors. Consider the below example

layout.xml

        <TextView
            android:id="@+id/location"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="0dp"
            android:layout_marginTop="12dp" />

        <ImageView
            android:id="@+id/location"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_marginStart="33dp"
            android:layout_marginTop="5dp"
            app:srcCompat="@drawable/openLoc" />

LocationActivity.java

setContentView(R.layout.activity_profile); //inflated layout
txtLocation = (TextView) findViewById(R.id.location);

Here you will face the problem in Activites because it will be confused that which element should be picked from two.

Btw YES you can use same IDs in the different layouts because it won't make any runtime error as it will search IDs on inflated layout only.

EDIT: You can have same IDs in the same layout. It causes an issue when you call it by findViewById() and throws similar exception

java.lang.ClassCastException
android.support.v7.widget.AppCompatImageView cannot be cast to android.widget.TextView

Suggestion: I don't know why you want to assign same IDs to two elements but if you want readability then I would suggest you to set ids in a way that elements can be easily identifiable by ID like android:id="@+id/txtLocation" android:id="@+id/imgLocation" it makes it easy to identify element type just by reading ID. You can make it even easier by appending layout name in beginning like android:id="@+id/profileTxtLocation". Now this will help you while coding as autocomplete feature will assist you. Just type layout name you will get the list of all layout elements, then you will type the kind of element you get the list of all asked elements(es: textViews) in layout.




回答2:


You theoretically can but it's highly advised not to. Duplicate IDs within same layout since it will prevent finding view by ID (You will need to iterate over children or otherwise reference them), and cause collision/outright crash when those views will attempt to store/restore their savedInstanceState.



来源:https://stackoverflow.com/questions/51342299/can-i-have-2-different-views-with-same-id-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!