2016-09-27 81 views
-1

我加入一個的LinearLayout視圖中顯示,這種方式:動態添加TextInputLayout不LinearLayout中

LinearLayout ll=(LinearLayout)findViewById(R.id.linearlayout); 
TextInputLayout til=new TextInputLayout(MainActivity.this); 
til.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
LinearLayout.LayoutParams.WRAP_CONTENT)); 
Log.i("TAG","BEFORE: "+ll.getChildCount()); 
ll.addView(til); 
Log.i("TAG","AFTER: "+ll.getChildCount()); 

這樣,沒有顯示直到對象,但補充說,因爲在第二日誌我看到這個數字增加了一個,我剛剛添加的觀點。

爲什麼我看不見?如何在佈局中顯示新視圖?

謝謝。

+0

我認爲它不會顯示,因爲你的'TextInputLayout'是空的。嘗試在'TextInputLayout'中添加'TextInputEditText'。 – pike

+0

嘗試膨脹它:http://stackoverflow.com/questions/31294230/textinputlayout-not-showing-when-view-added-programmatically – codemirel

回答

1

我想你忘記了什麼是添加一個EditText或TextInputEditText到TextInputLayout。

Android的文件說:

[TextInputLayout是]佈局它包裝一個EditText(或子孫)來顯示一個浮動標籤時的提示被隱藏,由於用戶輸入的文本。

EditText editText = new EditText(this); 

    RelativeLayout.LayoutParams editTextParams = new RelativeLayout.LayoutParams(
      RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
    editText.setLayoutParams(editTextParams); 

    editText.setTextSize(16); 
    editText.setTextColor(getResources().getColor(R.color.black)); 
    editText.setHint("hint"); 
    editText.setHintTextColor(getResources().getColor(R.color.gray)); 

    textInputLayout.addView(editText, editTextParams); 
+0

這是錯誤的。非常感謝你。 – Fustigador

0

til零高度。而不是使用這樣的:

til.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));

+0

這種方式是之前我做了一些改變,並沒有奏效。 – Fustigador

1

TextInputLayout什麼,而不必EditText的孩子。

創建如下佈局文件text_input_layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 

    <EditText 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 

</android.support.design.widget.TextInputLayout> 

現在,添加,只是誇大這種佈局和下面addView()LinearLayout

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearlayout); 
TextInputLayout textInputLayout = (TextInputLayout) LayoutInflator.from(this).inflate(R.layout.text_input_layout, null); 
linearLayout.addView(textInputLayout); 

希望這有助於...

注意:您也可以將TextInputEditText作爲0123子項