在android中通过其类类型返回子元素

时间:2016-08-20 14:16:30

标签: java android

我有question.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:layout_marginBottom="10dp"
        android:textColor="#239"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:layout_gravity="center_horizontal" />
    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></RadioGroup>
</LinearLayout>

返回给定parentid的第一个子视图的函数:

public View findViewByType(int parentId, Class<?> type){
    LinearLayout rootLinearLayout = (LinearLayout) findViewById(parentId);
    int count = rootLinearLayout.getChildCount();
    for (int i = 0; i < count; i++) {
        View v = rootLinearLayout.getChildAt(i);
        //Toast.makeText(getApplicationContext(), v.getClass().getName(),Toast.LENGTH_LONG).show();
        if (v.getClass() ==  type) return v;
    }
    return null;
}

我使用question.xml布局对视图进行充气,然后尝试从中获取RadioGroup:

        LinearLayout q = (LinearLayout)getLayoutInflater().inflate(R.layout.question, null);
        RadioGroup rg = (RadioGroup) findViewByType(q.getId(), RadioGroup.class);

rgnull

当我测试它时:

q.getChildAt(0).getClass().GetName();  //return TextView = Correct
q.getChildAt(1).getClass().GetName(); //returns RadioGroup = Correct

但在函数findViewByType循环中,v的值为:

i = 1是TextView,这是正确的

i = 2是LinearLayout INCORRECT

我做错了什么?

顺便说一句,我试着在调用函数之前为膨胀的LinearLayout设置Id,但结果是一样的。

1 个答案:

答案 0 :(得分:1)

嗯.. LinearLayoutRadioGroup的封闭类我会说相当于

v.getClass().isAssignableFrom(type) && (type.isInstance(v))//did it work?

也许这样呢?

(v.getClass() ==  type) || (v.getClass().isAssignableFrom(type) && 
                          v.getClass().equals(type.getEnclosingClass()))