动态添加的TextInputLayout在LinearLayout中不显示

Dynamically added TextInputLayout is not shown in LinearLayout

我在 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());

这样,til 对象没有显示,但它被添加了,因为在第二个日志中我看到数字增加了一个,我刚刚添加的视图。

为什么我看不到?如何在布局中显示新视图?

谢谢。

til 的高度为零。改用这个:

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

我认为您忘记了将 EditText 或 TextInputEditText 添加到 TextInputLayout。

android 文档说:

[TextInputLayout is a] Layout which wraps an EditText (or descendant) to show a floating label when the hint is hidden due to the user inputting text.

    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);

TextInputLayout 没有 EditText 作为 child.

什么都不是

创建布局文件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 作为 TextInputLayout

的 Child