Fustigador Fustigador - 2 months ago 16
Android Question

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.

Answer

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