通过代码创建的TextInputLayout未显示外框,该如何修复?
解决Material风格EditText无边框问题
我想要创建带边框的Material风格EditText字段,当前使用的代码如下:
TextInputLayout textInputLayout = new TextInputLayout(MainActivity.this); textInputLayout.setHint("name:"); TextInputEditText editText = new TextInputEditText(MainActivity.this); editText.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); editText.setTypeface(Typeface.create("sans-serif-smallcaps", Typeface.NORMAL)); editText.setScaleX(0.99f); textInputLayout.addView(editText); textInputLayout.setBoxBackgroundMode(TextInputLayout.BOX_BACKGROUND_OUTLINE); textInputLayout.setBoxCornerRadii(10, 10, 10, 10); textInputLayout.setPadding(10, 10, 10, 10); textInputLayout.setBoxStrokeWidth(2); layout.addView(textInputLayout);
但运行后EditText没有任何边框,尝试设置textInputLayout.setBoxBackgroundMode(TextInputLayout.BOX_BACKGROUND_FILLED);后问题依旧,请问该如何解决?
解决方案:
确认Material Components依赖已引入
确保模块级build.gradle中添加了Material库依赖:dependencies { implementation 'com.google.android.material:material:1.9.0' // 可使用更高稳定版本 }使用Material主题上下文
TextInputLayout需要Material主题支持,二选一即可:- 给Activity设置Material主题(在
styles.xml中):
<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar"> <!-- 自定义主题属性 --> </style>- 创建TextInputLayout时传入带Material样式的上下文:
Context themedContext = new ContextThemeWrapper(MainActivity.this, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox); TextInputLayout textInputLayout = new TextInputLayout(themedContext);- 给Activity设置Material主题(在
调整EditText的布局高度
你给EditText设置了MATCH_PARENT高度,可能会遮挡TextInputLayout的边框背景,建议改为:editText.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));显式设置边框颜色
若边框颜色与背景色一致会导致不可见,手动指定边框颜色:// 设置默认边框颜色 textInputLayout.setBoxStrokeColor(ContextCompat.getColor(MainActivity.this, R.color.your_stroke_color)); // 或设置不同状态下的颜色列表(推荐) textInputLayout.setBoxStrokeColorStateList(ContextCompat.getColorStateList(MainActivity.this, R.color.box_stroke_color));
内容的提问来源于stack exchange,提问作者user21742102
相关产品推荐
相关产品推荐

