2017-02-24 25 views
-1

我的文件layout.xmlAndroid版本:找不到父視圖

<android.support.design.widget.TextInputLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     > 
     <EditText 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/edit_name" 
      android:hint="@string/name" 
      /> 
</android.support.design.widget.TextInputLayout> 

當我試圖讓家長在活動

EditText edit_name= (EditText) view.findViewById(R.id.edit_name); 
TextInputLayout textInputLayout = (TextInputLayout) edit_name.getParent(); 

錯誤

java.lang.ClassCastException:android.widget.FrameLayout不能轉換爲androi d.support.design.widget.TextInputLayout

+0

您是否在下面檢查了我的答案,對您有用嗎? –

回答

0

你需要設置ID在TextInputLayout與ID綁定,而不是用的getParent()。

謝謝。

+0

感謝您的幫助 –

0

一種解決方法是將一個ID設置爲這個TextInputLayout:

<android.support.design.widget.TextInputLayout 
     android:id="@+id/edit_input_layout" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     > 
     <EditText 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/edit_name" 
      android:hint="@string/name" 
      /> 
</android.support.design.widget.TextInputLayout> 

而且

EditText edit_name= (EditText) view.findViewById(R.id.edit_name); 
TextInputLayout textInputLayout = (TextInputLayout) view.findViewById(R.id.edit_input_layout); 
0

首先,你將有一個ID添加一個設置爲您TextInputLayout這樣的:

<android.support.design.widget.TextInputLayout 
     android:id="@+id/text_input_layout" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     > 
     <EditText 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/edit_name" 
      android:hint="@string/name" 
      /> 
</android.support.design.widget.TextInputLayout> 

之後,您可以像獲取EditText一樣獲取TextInputLayout。

0

也許你想嘗試TextInputLayout的不同。

,而不是使用:

TextInputLayout textInputLayout = (TextInputLayout) edit_name.getParent(); 

,你可能會想嘗試:

XML:

<android.support.design.widget.TextInputLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="testId"  > 
     <EditText 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/edit_name" 
      android:hint="@string/name" 
      /> 
</android.support.design.widget.TextInputLayout> 

代碼:

TextInputLayout textInputLayout = (TextInputLayout) findViewById(R.id.testId); 
0

注意:TextInputLayout下的實際視圖層次結構不是 ,保證與用XML編寫的視圖層次結構匹配。因此,對TextInputLayout的子項(如 TextInputEditText)的getParent()調用 可能不會返回TextInputLayout本身,而是 而不是中間視圖。如果您需要直接訪問View, 會設置android:id並使用findViewById(int)。

即解決您必須使用findViewById代替getParent問題。

來源是Android official documents