Reputation: 439
I'm trying to apply TextInputLayout theme programmatically to create a custom edit text once and use it anywhere.
This is my Custom edit text class:
package com.enjoyapps.weddingapp.view;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import androidx.appcompat.view.ContextThemeWrapper;
import com.enjoyapps.weddingapp.R;
import com.google.android.material.textfield.TextInputLayout;
public class CustomEditText extends TextInputLayout {
public CustomEditText(Context context) {
super(new ContextThemeWrapper(context, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox));
init();
}
public CustomEditText(Context context, AttributeSet attrs) {
// super(context, attrs);
super(new ContextThemeWrapper(context, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox), attrs);
init();
}
public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(new ContextThemeWrapper(context, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox), attrs, defStyleAttr);
init();
}
private void init() {
setBoxStrokeColor(Color.BLUE);
setBoxCornerRadii(50,50,50,50);
setBoxBackgroundColor(Color.BLUE);
}
}
As you can see, in Constructor I'm setting the style with :
new ContextThemeWrapper(context, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox)
And when i add the custom edit text to xml , it's not getting the attribute that I set in init method.
But when I apply the same theme in xml, it's working and getting the all attribute from init method.
<com.enjoyapps.weddingapp.view.CustomEditText
android:layout_width="300dp"
android:layout_centerInParent="true"
android:layout_height="50dp">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</com.enjoyapps.weddingapp.view.CustomEditText>
Upvotes: 1
Views: 746
Reputation: 2254
It took a bit of digging to find out the problem. Apparently, TextInputLayout
uses a boxBackgroundMode
in order to use certain attributes from different styles.
In addition to ContextThemeWrapper
, you have to set the boxBackgroundMode
for your TextInputLayout
.
Therefore, if you are using :
FilledBox
: you need to useBOX_BACKGROUND_FILLED
OutlinedBox
: you need to useBOX_BACKGROUND_OUTLINE
In your case, just add setBoxBackgroundMode(BOX_BACKGROUND_OUTLINE)
into your init()
:
private void init() {
// ... some styling here
setBoxBackgroundMode(BOX_BACKGROUND_OUTLINE);
}
Upvotes: 1
Reputation: 167
Which style using your app? Just add to your main style:
<item name="editTextStyle">@style/YourStyle</item>
Example:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="editTextStyle">@style/YourStyle</item>
</style>
Upvotes: 1