I dynamically create textInputlayout and add it to my lienarlayot using the code below:
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);
I want to change boxStrokeColor , CursorColor and HintTextColor.
I use the following code block to change boxStrokeColor
til.setBoxStrokeColor(getResources().getColor(R.color.white));
But that code block only change the boxStrokeColor of TextInputLayout (white) when I click the TextInputLayout ,without click it's color is black. How can I set it's color white ?
You have to use a selector(ColorStateList
) otherwise the single value will be applied to the box only if focused.
Use the method setBoxStrokeColorStateList
til.setBoxStrokeColorStateList(ContextCompat.getColorStateList(this.R.color.selector))
where the selector
is something like:
<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>
Note: it requires at least the version 1.2.0
of material components library.
There is an alternative if you want to use a style defined in xml:
Define in attrs.xml
a custom attribute:
<attr name="customTextInputStyle" format="reference" />
then in your theme add this attribute:
<style name="AppTheme" parent="Theme.MaterialComponents.*">
<!-- ..... -->
<item name="customTextInputStyle">@style/Widget.App.TextInputLayout.OutlinedBox</item>
</style>
Now you can add all the properties in the new 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>
Finally create your TextInputLayout
with:
TextInputLayout til = new TextInputLayout(this,null,R.attr.customTextInputStyle);