LinearLayout中未显示动态添加的TextInputLayout

时间:2016-09-27 14:22:38

标签: android android-view

我在LinearLayout中添加一个View,这样:

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对象没有显示,但是它被添加了,因为在第二个日志中我看到数字增加了1,我刚刚添加的视图。

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

谢谢。

3 个答案:

答案 0 :(得分:2)

我认为您忘记的是将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);

答案 1 :(得分: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作为TextInputLayout的孩子

答案 2 :(得分:0)

til的高度为零。请改用:

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