Fustigador
Fustigador

Reputation: 6469

Dynamically added TextInputLayout is not shown in LinearLayout

I am adding a View in a LinearLayout, this way:

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

This way, the til object is not shown, but it IS added, because in the second log I see the number has incremented by one, the view I just added.

Why can't I see it? how to show the new view in the layout?

Thank you.

Upvotes: 0

Views: 2385

Answers (3)

Chintan Soni
Chintan Soni

Reputation: 25287

TextInputLayout is nothing without having EditText as child.

Create a layout file text_input_layout.xml as below:

<?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>

Now, to add, simply inflate this layout and addView() to LinearLayout as below:

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

Hope this helps...

Note: You can also have TextInputEditText as Child of TextInputLayout

Upvotes: 1

Niccol&#242; Passolunghi
Niccol&#242; Passolunghi

Reputation: 6024

I think what you are forgetting is to add an EditText or a TextInputEditText to the TextInputLayout.

The android documentation says:

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

Upvotes: 3

Vyacheslav
Vyacheslav

Reputation: 27221

The til has zero height. Use this instead:

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

Upvotes: 0

Related Questions