Android:以编程方式添加TextInputLayout
来源:爱站网时间:2021-09-17编辑:网友分享
我正在尝试以编程方式将带有EditText的TextInputLayout添加到LinearLayout。我的方法:TextInputLayout textInputLayout = new TextInputLayout(new ContextThemeWrapper(getContext(),R ....
问题描述
我正在尝试以编程方式将带有EditText的TextInputLayout添加到LinearLayout。我的方法:
TextInputLayout textInputLayout = new TextInputLayout(new ContextThemeWrapper(getContext(), R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox));
textInputLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textInputLayout.setHintTextAppearance(R.style.Base_Widget_MaterialComponents_TextInputLayout_TextInputLayout);
TextInputEditText editText = new TextInputEditText(getContext());
editText.setHint("test");
textInputLayout.addView(editText, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(textInputLayout);
但是,结果看起来非常有问题:
很奇怪,通过XML添加相同的TextInputLayout的工作是:
现在,我需要补充说,在升级到材料1.1之前,程序化方法已经奏效。我仅使用材料组件。我该如何解决?
思路:
具有样式属性,必须使用setBoxBackgroundMode()
方法才能使用OutlineBox样式。除此之外,您还应该使用TextInputLayout
的context
创建TextInputEditText
。检查以下:
textInputLayout.setBoxBackgroundColor(ContextCompat.getColor(getContext(), android.R.color.white));
textInputLayout.setBoxBackgroundMode(TextInputLayout.BOX_BACKGROUND_OUTLINE);
//Must use context of textInputLayout
TextInputEditText editText = new TextInputEditText(textInputLayout.getContext());