Android 如何获取添加到 ViewGroup(layout) 的特定视图或 ViewGroup 的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3334754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the index of particular view OR ViewGroup which is added to the ViewGroup(layout)
提问by user373885
<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>
how to retrieve the index of linearLayout which has "llIndex" as id. Thanks
如何检索以“llIndex”为 id 的 linearLayout 的索引。谢谢
回答by Romain Guy
Very simple - call the indexOfChild function on the view's parent:
非常简单 - 在视图的父级上调用 indexOfChild 函数:
LinearLayout addNoteLayout = (LinearLayout) findViewById(R.id.llAddNote);
int index = ((ViewGroup) addNoteLayout.getParent()).indexOfChild(addNoteLayout);
回答by Dan Lew
When you create the XML, there is a file yourpackage.generated.R.java that is created with all the ids/drawables/etc in it. So to reference it, import the generated R.java into your class, then do this (assuming you're in an Activity):
创建 XML 时,会创建一个文件 yourpackage.generated.R.java,其中包含所有 ids/drawables/etc。因此,要引用它,请将生成的 R.java 导入您的类,然后执行此操作(假设您在 Activity 中):
setContentView(R.layout.my_content);
LinearLayout addNoteLayout = (LinearLayout) findViewById(R.id.llAddNote);