有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何获取安卓中给定xml文件中的组件列表及其id?

。我是安卓的新手。对于某些需要,我需要获得所有组件(即文本视图、按钮、编辑文本、图像视图、微调器、复选框等)以及我的布局xml文件中的ID。 假设我有以下xml文件sample.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:orientation="vertical" >

    <TextView
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:layout_centerHorizontal="true"
        安卓:layout_centerVertical="true"
        安卓:text="@string/hello_world" />

    <Button
        安卓:id="@+id/button1"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="Button" />


    <CheckBox
        安卓:id="@+id/checkBox1"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="CheckBox" />

    <RadioButton
        安卓:id="@+id/radioButton1"
        安卓:layout_width="wrap_content"
        安卓:layout_height="wrap_content"
        安卓:text="RadioButton" />

    <EditText
        安卓:id="@+id/editText1"
        安卓:layout_width="match_parent"
        安卓:layout_height="wrap_content"
        安卓:ems="10" >
        <requestFocus />
    </EditText>



</LinearLayout>

目前我只有xml文件的id。我需要获取所有组件和ID,以便我可以使用java代码修改它们的文本。简而言之,我需要某种解析。 假设我在xml文件中除了id之外什么都不知道

所以请帮帮我。提前谢谢你

实际上,我需要更改布局中每个文本视图的文本,比如说,我需要在每个文本视图的文本末尾添加*ath


共 (1) 个答案

  1. # 1 楼答案

    好吧,你没有办法实现你想要的

    如果所有ID都是在xml布局文件中创建和定义的——您必须在代码中调用它们——但您必须知道它们的给定ID

    如果您通过代码创建ID,例如textView.setId(1234);,那么您就可以跟踪所有名称,并对它们执行任何操作

    所以,不幸的是,我不认为你想要什么是可能的