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

Can i have 2 different views with same id in android(我可以在android中有2个具有相同ID的不同视图吗)

本文介绍了我可以在android中有2个具有相同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 ?

解决方案

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.

这篇关于我可以在android中有2个具有相同ID的不同视图吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:我可以在android中有2个具有相同ID的不同视图吗

基础教程推荐