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

问题描述:

TextView和ImageView具有相同的Id是否正确?
因为他们属于一个实体我给他们两个相同的Id。
如果是..那么如何通过id单独找到这些视图?

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 ?


TextView和ImageView的ID是否正确?

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

简答:

长答案:使用相同的ID 是正确的,因为这样做会导致运行时错误。请考虑以下示例

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

layout.xml

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

LocationActivity.java

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

在这里,您将面临Activites中的问题,因为它将混淆应从两个元素中选择哪个元素。

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

Btw YES 您可以在不同的布局中使用相同的ID,因为它不会产生任何运行时错误,因为它会在膨胀的布局上搜索ID只要。

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.

编辑:您可以在同一版面中使用相同的ID。当您通过 findViewById()调用它时会引发问题并抛出类似的异常

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

建议:我不知道你为什么要为两个元素分配相同的ID,但如果你想要可读性,那么我建议你以这样的方式设置id元素可以通过ID轻松识别,如 android:id =@ + id / txtLocation android:id =@ + id / imgLocation只需读取ID即可轻松识别元素类型。您可以通过在 android:id =@ + id / profileTxtLocation开头添加布局名称来使其更加轻松。现在,这将帮助您编码为自动完成功能将帮助您。只需键入布局名称,您将获得所有布局元素的列表,然后您将在布局中键入所有要求元素(es:textViews)列表的元素类型。

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.