Search code examples
androidautocompletetextviewandroid-textinputlayout

How to add autocompletetext in textinputlayout programatically in android


I created a layout in main activity and now I am trying to call this method where I need to add this view in my main layout. Its not behaving the same way as TextInputLayout Behaves.

Please check my code and let me know what should I change.

public static View getTypeAHeadView(Context context) {

    RelativeLayout layout = new RelativeLayout(context);
    try {
        RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layout.setLayoutParams(lp1);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(0, 5, 0, 0);
        TextInputLayout textInputLayout = new TextInputLayout(context);
        AutoCompleteTextView autoCompleteTextView = new AutoCompleteTextView(context);
        autoCompleteTextView.setHeight(R.dimen.dim_40);
        autoCompleteTextView.setWidth(LinearLayoutCompat.LayoutParams.MATCH_PARENT);
        autoCompleteTextView.setTextSize(R.dimen.dim_20_sp);
        autoCompleteTextView.setLines(1);
        autoCompleteTextView.setDropDownHeight(R.dimen.dim_200);
        autoCompleteTextView.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,"));
        autoCompleteTextView.setPadding(10, 0, 0, 0);
        autoCompleteTextView.setSingleLine(true);
        autoCompleteTextView.setLayoutParams(lp);

        textInputLayout.addView(autoCompleteTextView);

        layout.addView(textInputLayout);
    } catch (Exception e) {
        e.printStackTrace();
    }
  /*parent.addView(text);
    parent.addView(editText);*/
    return layout;
}

Solution

  • I'm not entirely certain but perhaps try defining layout parameters for the TextInputLayout you are adding programmatically.