在XML文件中,我们可以将一个ID分配给如下所示的视图android:id="@+id/something"
然后CallfindViewById()
但是,当以编程方式创建视图时,如何分配ID?
个人觉得setId()
与默认赋值不同。setId()
是额外的。
有人可以提供一些意见吗?
发布于 2017-12-29 08:46:56
可以看下如下代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/placeholder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
MyActivity.java以编程方式定义一些添加视图(通过代码):
int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
TextView tv = new TextView(this.getApplicationContext());
// One new TextView will also be assigned an id==12:
tv.setId(i);
placeholder.addView(tv);
}
发布于 2017-12-29 09:25:58
可以使用View.setId(integer)
。在XML中,即使设置了字符串id,也会将其转换为整数。
根据
View
文献资料 标识符在此视图的层次结构中不必是唯一的。标识符应该是正数。所以你可以使用任何你喜欢的正整数,但是在这种情况下,可以有一些与id等价的视图。如果您想在层次结构中搜索某个视图,使用一些关键对象调用setTag可能会很方便。
发布于 2017-12-29 10:39:27
可以CallsetId(value)
在具有任何(正整数)值的视图中,然后在父容器中使用findViewById(value)
https://stackoverflow.com/questions/-100001313
复制相似问题