访问android中任何视图的父视图
在xml代码中的TextInputLayout中有一个TextInputInputText访问android中任何视图的父视图,android,Android,在xml代码中的TextInputLayout中有一个TextInputInputText <android.support.design.widget.TextInputLayout android:id="@+id/textfieldContainer2" android:layout_width="match_parent" android:layout_height="wrap_content" app:errorEn
<android.support.design.widget.TextInputLayout
android:id="@+id/textfieldContainer2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:errorEnabled="true"
app:errorTextAppearance="@style/customErrorTextColor"
app:hintTextAppearance="@style/customHintTextAppearance"
app:layout_constraintTop_toBottomOf="@id/textfieldContainer">
<android.support.design.widget.TextInputEditText
android:id="@+id/bottomtextfield"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="add bottom text"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" />
</android.support.design.widget.TextInputLayout>
但是这行代码抛出java.lang.IllegalStateException
问题:
我在这里做错了什么?如何通过TextInputInputText的引用获取任何TextInputText的父TextInputLayout
堆栈跟踪
获取对包含TextInputText的TextInputLayout的引用可以按以下步骤进行:
TextInputEditText textfield = findViewById(R.id.bottomtextfield);
ViewGroup containingLayout = (ViewGroup) textfield.getParent();
TextInputLayout textInputLayout = (TextInputLayout) containingLayout.getParent();
这是因为TextInputLayout上有一个FrameLayout,其中包含关联的TextInputInputText。xml中的视图层次结构可能与android返回的视图层次结构不同。因此getParent可能不会返回预期的视图 因此,您应该更喜欢使用:
TextInputLayout parentInputLayout = findViewById(R.id.textfieldContainer2);
完整的java stacktrace是什么?@pskink发布的。原因:java.lang.ClassCastException:android.widget.FrameLayout无法转换为android.support.design.widget.TextInputLayout
TextInputEditText textfield = findViewById(R.id.bottomtextfield);
ViewGroup containingLayout = (ViewGroup) textfield.getParent();
TextInputLayout textInputLayout = (TextInputLayout) containingLayout.getParent();
TextInputLayout parentInputLayout = findViewById(R.id.textfieldContainer2);