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的不同视图吗
基础教程推荐
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01