如何获取子视图索引?

时间:2015-09-14 22:22:38

标签: android android-layout android-fragments

如果我有:

public class SectionView extends AbstractSectionView {
private final EditText nameET;

private final EditText valueET;

private final TextView tapHere;

public SectionView(Context c) {
    super(c);
    LayoutInflater inflater = LayoutInflater.from(context);
    inflater.inflate(R.layout.view_section, this);
}     

布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
<EditText
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

<RelativeLayout
        android:id="@+id/my_section"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:onClick="startNextScreen">
    <TextView
        android:id="@+id/tapHereLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="Next Screen" />
    <EditText
        android:id="@+id/value" ....

使用此布局将多个这些SectionView作为子项添加到名为MyFragment的片段中:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        android:id="@+id/section_views_container"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <!-- SectionViews added here by java code -->
    </LinearLayout>   

我将onClick侦听器添加到RelativeLayout“my_section”,所以我在片段的Activity中有这个click处理程序:

/* v is the RelativeLayout called my_section in the SectionView's     
 * layout
 */
public void startNextScreen(View v) {
    // SectionView root view
    RelativeLayout sectionView = (RelativeLayout)v.getParent();

    /* f is the fragment that holds a LinearLayout that has   
     * SectionView children added at runtime 
     */
    MyFragment f = (MyFragment)getSupportFragmentManager().findFragmentByTag("MyFragment");
    LinearLayout sectionViewsContainer = (LinearLayout)f.getView().findViewById(R.id.section_views_container);

    for(int childIndex=0; childIndex < sectionViewsContainer.getChildCount(); childIndex++) {
        SectionView child = (SectionView)sectionViewsContainer.getChildAt(childIndex);

        if(child.equals(sectionView)) {
            tappedIndex = childIndex;
            break;
        }
     }

equals比较永远不会解析为true,因为我将SectionView类型与RelativeLayout类型进行比较。但RelativeLayout是根视图,所以不是它也是SectionView?

单击其中一个剖面视图后,如何使用相同的类型引用它和循环内的当前子视图?转换单击的视图“v”或子视图会抛出ClassCastException。 AbstractSectionView从FrameLayout扩展而来,我无法改变它。

1 个答案:

答案 0 :(得分:0)

您需要获取SectionView的子视图而不是getParent