2016-08-20 52 views
0

返回的子元素通过其类类型我有question.xml:android系统

<?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循环,对于诉值:

I = 1是TextView这是正确的

I = 2是LinearLayout这就是INCORRECT

我在做什么错?

顺便说一下,我试图在调用函数之前设置Id为虚拟的LinearLayout,但结果是相同的。

回答

1

uhmm .. LinearLayout是封闭类的RadioGroup我会说去为这个而

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

也许这相当?

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