如何在 android 中以编程方式在 textinputlayout 中添加自动完成文本

How to add autocompletetext in textinputlayout programatically in android

我在主布局中创建了一个布局 activity,现在我试图在我需要在主布局中添加此视图的地方调用此方法。它的行为方式与 TextInputLayout 行为方式不同。

请检查我的代码,让我知道我应该更改什么。

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

我不完全确定,但也许可以尝试为您以编程方式添加的 TextInputLayout 定义布局参数。