【问题标题】:Get Ids Dynamically using findViewById() in Android using Java使用 Java 在 Android 中使用 findViewById() 动态获取 ID
【发布时间】:2022-06-10 20:18:23
【问题描述】:
在我的XML 布局中,我有一些TextView 和ids,比如slot0、slot1...slot15。
有没有什么方法可以像下面这样在java中动态生成对应的Id?
findViewById(R.id.*customStringForId*)
然后使用for 循环访问每个TextView?
我目前无法使用findViewById(R.id.*customStringForId*),因为我在XML 中找不到它。
【问题讨论】:
标签:
java
android
findviewbyid
【解决方案1】:
从您的 xml 访问组件是一种不好的做法
您需要使用 findViewById 为 id 设置手册,以便告诉 java 类,如果在您的 xml 中存在您已经设置的带有 id 的 textview,并允许您执行任何操作,例如实现 onclick 事件、settext 等。
如果你找不到你的 id,你需要检查你的 java 中的 setContentView 是否指向你的 xml。
【解决方案2】:
首先要知道,通过id访问XML Layout的唯一方式是静态的
但是有一些方法可以解决您的问题,但您应该在问题中写下您的布局,让我们知道您是如何设计布局的。
但是例如,如果您有一个 TextViews 内部布局列表,如下所示:
<LinearLayout
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/slot0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="example" />
<TextView
android:id="@+id/slot1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="example" />
<TextView
android:id="@+id/slot2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="example" />
</LinearLayout>
您可以通过如下布局动态访问TextView:
public TextView getTextView(int index){
return ((LinearLayout) findViewById(R.id.layout)).getChildAt(index)
}