我动态创建 textInputlayout 并使用以下代码将其添加到我的 lienarlayot:
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(10,10,10,10);
til.setLayoutParams(params);
til.setHint("Label");
til.setId(i+1);
TextInputEditText et = new TextInputEditText(til.getContext());
et.setSingleLine(true);
til.addView(et);
til.setBoxCornerRadii(R.dimen.CornerRadious,R.dimen.CornerRadious,R.dimen.CornerRadious,
R.dimen.CornerRadious);
information.addView(til);
我想更改 boxStrokeColor 、 CursorColor 和 HintTextColor。
我使用以下代码块来更改 boxStrokeColor
til.setBoxStrokeColor(getResources().getColor(R.color.white));
但是当我单击 TextInputLayout 时,该代码块仅更改 TextInputLayout 的 boxStrokeColor(白色),没有单击它的颜色是黑色。我怎样才能将它的颜色设置为白色?
最佳答案
您必须使用选择器 (ColorStateList
),否则只有在获得焦点时才会将单个值应用于框。
使用方法setBoxStrokeColorStateList
til.setBoxStrokeColorStateList(ContextCompat.getColorStateList(this.R.color.selector))
选择器
是这样的:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/...." android:state_focused="true"/>
<item android:color="@color/...." android:state_hovered="true"/>
<item android:color="@color/...." android:state_enabled="false"/>
<item android:color="@color/...."/>
</selector>
注意:需要至少1.2.0
版本的 Material 组件库。
如果你想使用在 xml 中定义的样式,还有一个选择:
在 attrs.xml
中定义一个自定义属性:
<attr name="customTextInputStyle" format="reference" />
然后在你的主题中添加这个属性:
<style name="AppTheme" parent="Theme.MaterialComponents.*">
<!-- ..... -->
<item name="customTextInputStyle">@style/Widget.App.TextInputLayout.OutlinedBox</item>
</style>
现在您可以添加新样式中的所有属性:
<style name="Widget.App.TextInputLayout.OutlinedBox" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<item name="boxStrokeColor">@color/boxstroke_selector</item>
<!-- .... -->
<item name="materialThemeOverlay">@style/ThemeOverlay.App.TextInputEditText.OutlinedBox</item>
</style>
<style name="ThemeOverlay.App.TextInputEditText.OutlinedBox"
parent="ThemeOverlay.MaterialComponents.TextInputEditText.OutlinedBox">
<!-- to change the cursor color -->
<item name="colorControlActivated">@color/teal_200</item>
</style>
最后创建你的TextInputLayout
:
TextInputLayout til = new TextInputLayout(this,null,R.attr.customTextInputStyle);
关于android - 如何在 Android 中更改 TextInputLayout 的 boxStrokeColor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67035056/
相关文章:
java - 如何给java.net.http.HttpClient GET请求添加参数?
modbus - Minimalmodbus:在同一个串口上读取多个从机
reactjs - React Portal 中 nextJS 应用程序的转发样式
python - 类型错误 : forward() takes 2 positional argum
c# - 使用 Newtonsoft.JSON 自定义转换器读取具有不同输入的 json
git - 如何使用 gitlab-ci.yml 进行简单的 pull ?