如何获取特定视图的索引或ViewGroup添加到ViewGroup(布局)

use*_*885 31 android

<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:layout_margin="24dip"
    android:text="Add Notes" />
<TableLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:layout_marginLeft="24dip"
    android:layout_marginRight="24dip" android:id="@+id/tlNotes"
    android:stretchColumns="0">
</TableLayout>

<Button android:id="@+id/bAddNoteLine"
    android:layout_marginLeft="24dip" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="ADD">
</Button>

<LinearLayout android:id="@+id/llIndex"
    android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:layout_margin="21dip"
    android:gravity="center">
    <Button android:id="@+id/bSaveSubjectiveNote"
        android:layout_width="192dip" android:layout_height="wrap_content"
        android:text="Save" />
    <Button android:id="@+id/bDiscardSubjectiveNote"
        android:layout_width="192dip" android:layout_height="wrap_content"
        android:layout_marginLeft="48dip" android:background="@drawable/button"
        android:text="Discard" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

如何检索具有"llIndex"作为id的linearLayout的索引.谢谢

Rom*_*Guy 106

非常简单 - 在视图的父级上调用indexOfChild函数:

LinearLayout addNoteLayout = (LinearLayout) findViewById(R.id.llAddNote);
int index = ((ViewGroup) addNoteLayout.getParent()).indexOfChild(addNoteLayout);
Run Code Online (Sandbox Code Playgroud)


Dan*_*Lew -1

当您创建 XML 时,会创建一个包含所有 ids/drawables/etc 的文件 yourpackage. generated.R.java 。因此,要引用它,请将生成的 R.java 导入到您的类中,然后执行以下操作(假设您位于 Activity 中):

setContentView(R.layout.my_content);
LinearLayout addNoteLayout = (LinearLayout) findViewById(R.id.llAddNote);
Run Code Online (Sandbox Code Playgroud)