访问 Java 个文件中的 Android 个视图
Accessing Android Views in Java files
我设计了一个 RelativeLayout
,其中包含 TextView
和 ImageView
等子元素。我想要做的是从我在 XML 中创建的 RelativeLayout
创建一个 RelativeLayout
对象,这样我就可以访问它的子元素并修改它们(从 [=15= 更改图像] 并将文本更改为 TextView
)。我怎样才能做到这一点?大概是这样。
RelativeLayout lay = new "myrelativelayout";
ImageView img = lay.children[0];
TextView txt = lay.children[1];
谢谢!
XML:
<RelativeLayout
android:id="@+id/relative_layout_id"
...>
<TextView
android:id="@+id/textview_id"
.../>
</RelativeLayout>
Activity onCreate:
RelativeLayout lay = (RelativeLayout) findViewById(R.id.relative_layout_id);
要更改子项,请使用:
TextView child = (TextView) findViewById(R.id.textview_id);
child.setText(text);
或:
View child = lay.getChildAt(i);
要访问布局,我们使用 findViewById
方法。因此,要更改 ImageView
中的图像,您实际上不需要访问 RelativeLayout
.
我们通过其id访问任何元素的方式如下:
View v = (View)findViewById(R.id.view_id);
其中 view_id
是视图的 ID。
访问RelativeLayout
,因此,这段代码为:
RelativeLayout lay = (RelativeLayout) findViewById(R.id.relative_layout_id);
但是如果你只想改变TextView
中的文字,你就真的不需要上面的代码了。如果您对 TextView
:
进行类似的访问就足够了
TextView textView = (TextView) findViewById(R.id.id_of_textview);
textView.setText(text);
可以找到访问任何资源的通用方法 here。
我设计了一个 RelativeLayout
,其中包含 TextView
和 ImageView
等子元素。我想要做的是从我在 XML 中创建的 RelativeLayout
创建一个 RelativeLayout
对象,这样我就可以访问它的子元素并修改它们(从 [=15= 更改图像] 并将文本更改为 TextView
)。我怎样才能做到这一点?大概是这样。
RelativeLayout lay = new "myrelativelayout";
ImageView img = lay.children[0];
TextView txt = lay.children[1];
谢谢!
XML:
<RelativeLayout
android:id="@+id/relative_layout_id"
...>
<TextView
android:id="@+id/textview_id"
.../>
</RelativeLayout>
Activity onCreate:
RelativeLayout lay = (RelativeLayout) findViewById(R.id.relative_layout_id);
要更改子项,请使用:
TextView child = (TextView) findViewById(R.id.textview_id);
child.setText(text);
或:
View child = lay.getChildAt(i);
要访问布局,我们使用 findViewById
方法。因此,要更改 ImageView
中的图像,您实际上不需要访问 RelativeLayout
.
我们通过其id访问任何元素的方式如下:
View v = (View)findViewById(R.id.view_id);
其中 view_id
是视图的 ID。
访问RelativeLayout
,因此,这段代码为:
RelativeLayout lay = (RelativeLayout) findViewById(R.id.relative_layout_id);
但是如果你只想改变TextView
中的文字,你就真的不需要上面的代码了。如果您对 TextView
:
TextView textView = (TextView) findViewById(R.id.id_of_textview);
textView.setText(text);
可以找到访问任何资源的通用方法 here。