Can i have 2 different views with same id in android(我可以在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的不同视图吗


- 获取数字的最后一位 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 转换 ldap 日期 2022-01-01