我可以在android中有2个具有相同ID的不同视图吗

2022-01-24 00:00:00 android java imageview textview

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 ?

解决方案

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.

相关文章