Custom view looks duplicated when modifying items - android

I have this weird behavior when creating a custom view and modifying text and visibility, the view looks like it's rendered twice.
Here I'm changing the title and description text and showing the button Ver detalles
This is Custom view
class KitChoiceItemView #JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0): ConstraintLayout(context, attrs, defStyle) {
private var binding: KitChooiceItemViewBinding
private var isActive = false
init {
LayoutInflater.from(context).inflate(R.layout.kit_chooice_item_view, this, true)
binding = KitChooiceItemViewBinding.inflate(LayoutInflater.from(context), this, true)
}
fun setupToHome() {
binding.iconCircle.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_insc_home))
binding.titleText.text = "Entrega a domicilio"
binding.descriptionText.text = "Agrega una dirección para que podamos hacerte entrega de tu Kit a esa ubicación"
binding.priceText.visibility = View.VISIBLE
binding.detailsButton.visibility = View.GONE
binding.selectButton.setOnClickListener {
if (isActive) {
isActive = false
binding.cardView.background = ContextCompat.getDrawable(context, R.drawable.gray_border)
} else {
isActive = true
binding.cardView.background = ContextCompat.getDrawable(context, R.drawable.kit_item_selected)
}
}
}
fun setupToPlace() {
binding.iconCircle.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_insc_location))
binding.titleText.text = "Recoger kit en la expo"
binding.descriptionText.text = "Al seleccionar esta opción, omite el paso de entrega a domicilio y continuas para realizar el pago."
binding.priceText.visibility = View.GONE
binding.detailsButton.visibility = View.VISIBLE
binding.selectButton.setOnClickListener {
if (isActive) {
isActive = false
binding.cardView.background = ContextCompat.getDrawable(context, R.drawable.gray_border)
} else {
isActive = true
binding.cardView.background = ContextCompat.getDrawable(context, R.drawable.kit_item_selected)
}
}
}}
This is how Im implementing the custom view in my frame layout
<com.asdeporte.asdeportev2.ui.reusableview.inscription.KitChoiceItemView
android:id="#+id/address_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"/
<com.asdeporte.asdeportev2.ui.reusableview.inscription.KitChoiceItemView
android:id="#+id/delivery_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"/>
Setting the custom state
binding.addressView.setupToHome()
binding.deliveryView.setupToPlace()

I was inflating the layout twice, had to remove R.layout

Related

Memory Leak in Custom Alert dialog animation Android

I'm using an alert dialog to show an animation (green tick mark on success api call). But it's causing a memory leak if I press the home button before the animation ends.
To reproduce, I enabled "Finish Activities" in Developer Options.
Attaching the code below for "Tick Animation" and the custom dialog box which shows that animation.
SuccessAnimation.kt
class SuccessAnimation #JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null,
) : RelativeLayout(context, attrs) {
private val circleFadeInTime: Long
private val checkAnimationTime: Long
val postAnimationTime: Long
init {
inflate(context, R.layout.success_content, this)
val a = context.obtainStyledAttributes(attrs, R.styleable.SuccessAnimation, 0, 0)
try {
circleFadeInTime = a.getInteger(R.styleable.SuccessAnimation_circleAppearanceTime, DEFAULT_CIRCLE_TIME).toLong()
checkAnimationTime = a.getInteger(R.styleable.SuccessAnimation_checkMarkAnimationTime, DEFAULT_ANIMATION_TIME).toLong()
postAnimationTime = a.getInteger(R.styleable.SuccessAnimation_postAnimationTime, DEFAULT_POST_ANIMATION_TIME).toLong()
} finally {
a.recycle()
}
isClickable = true // Prevent anything else from happening!
}
val animationDuration = circleFadeInTime + checkAnimationTime + postAnimationTime
private val circle: View = findViewById(R.id.green_circle)
private val checkMark = findViewById<AnimatedCheckMark>(R.id.check_mark).apply { setAnimationTime(checkAnimationTime) }
private var onAnimationFinished: (() -> Unit)? = {}
/**
* Set a callback to be invoked when the animation finishes
* #param listener listener to be called
*/
fun setSuccessFinishedListener(listener: (() -> Unit)?) {
this.onAnimationFinished = listener
}
/**
* start the animation, also handles making sure the view is visible.
*/
fun show() {
if (visibility != VISIBLE) {
visibility = VISIBLE
post { show() }
return
}
circle.visibility = VISIBLE
circle.scaleX = 0f
circle.scaleY = 0f
val animator = ValueAnimator.ofFloat(0f, 1f)
animator.addUpdateListener { animation: ValueAnimator ->
val scale = animation.animatedFraction
circle.scaleY = scale
circle.scaleX = scale
circle.invalidate()
}
animator.duration = circleFadeInTime
animator.interpolator = OvershootInterpolator()
animator.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
checkMark!!.visibility = VISIBLE
invalidate()
checkMark.startAnimation { view: AnimatedCheckMark ->
view.postDelayed({
visibility = GONE
checkMark.visibility = INVISIBLE
circle.visibility = INVISIBLE
onAnimationFinished?.invoke()
}, postAnimationTime)
}
}
})
invalidate()
animator.start()
}
companion object{
private const val DEFAULT_CIRCLE_TIME = 300
private const val DEFAULT_ANIMATION_TIME = 500
private const val DEFAULT_POST_ANIMATION_TIME = 500
}
}
SuccessAnimationPopup.kt
class SuccessAnimationPopup(context: Context,
private val callback: () -> Unit) :
AlertDialog(context, android.R.style.Theme_Translucent_NoTitleBar) {
init {
window?.let {
it.setFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
)
it.setFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.success_animation_popup)
setCancelable(false)
val success = findViewById<SuccessAnimation>(R.id.success_animation)
success?.setSuccessFinishedListener {
dismiss()
callback()
}
success?.show()
}
}
It is being used like the following:
SuccessAnimationPopup(view.context) {}.show() I only have "view" here and not the activity.
Been trying to find the root cause. Have also added onDetachedFromWindow lifecycle callback in SuccessAnimation.kt and tried setting the onAnimationListener = null, still doesn't work.
What am I missing here?
Also, the AlertDialog constructor is not accepting a nullable context, hence I wasn't able to pass a WeakReference since it's nullable.

Add progressbar as compoundDrawable to button

I want to add a indeterminate progressbar to my custom button.
I'm using add setCompoundDrawablesWithIntrinsicBounds to add it to left.
But somehow progress bar animation doesn't appear.
//CustomButton.kt
fun addProgressbar () {
val progressBar = ProgressBar(context)
progressBar.isIndeterminate = true
progressBar.animate()
progressBar.setBackgroundColor(Color.RED)
progressBar.layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
progressBar.visibility = View.VISIBLE
setCompoundDrawablesWithIntrinsicBounds(
progressBar.indeterminateDrawable,
null,
ContextCompat.getDrawable(context, R.drawable.ic_baseline_notifications_black_24),
null
)
}
When I debug progressBar.isAnimating() returns false. I also tried to add a resource drawable with ContextCompat.getDrawable which works.
How can I make it work ?
class MyButton #JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : AppCompatButton(context, attrs, defStyle) {
private var progressDrawable: Drawable
init {
progressDrawable = ProgressBar(context).indeterminateDrawable.apply {
// apply any customization on drawable. not on progress view
setBounds(0, 0, 24.toPx, 24.toPx)
setTint(Color.WHITE)
}
compoundDrawablePadding = 4.toPx
}
var isLoading: Boolean = false
set(value) {
if (isLoading == value) return
field = value
val (startDrawable, topDrawable, endDrawable, bottomDrawable) = compoundDrawablesRelative
if (value) {
// add progress and keep others
setCompoundDrawablesRelative(
progressDrawable,
topDrawable,
endDrawable,
bottomDrawable
)
(progressDrawable as? Animatable)?.start()
} else {
// remove progress
setCompoundDrawablesRelative(
null,
topDrawable,
endDrawable,
bottomDrawable
)
(progressDrawable as? Animatable)?.stop()
}
}
override fun onDetachedFromWindow() {
(progressDrawable as? Animatable)?.stop()
super.onDetachedFromWindow()
}
}
PS: Slowness is related to recording/encoding. It works normally.

Android compound view in preview not showing height or contents

I'm creating a custom compound view which extends LinearLayout (also tried ConstraintLayout) which contains 2 child views. When the app is running the view lays out correctly, however in the preview window it shows as 0 height when I use wrap_content. When the view was extending ConstraintLayout it was rendering as match_parent when the view was set to wrap_content.
If I override onMeasure and force a size when isInEditMode it is still showing up as 0 height.
Can someone point out what I'm doing wrong?
This is the custom view class:
package com.classdojo.android.nessie
import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.annotation.ColorRes
import androidx.annotation.DimenRes
import androidx.annotation.DrawableRes
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.isVisible
import com.airbnb.paris.utils.getFont
import com.classdojo.android.nessie.icon.Icon
import kotlinx.android.synthetic.main.nessie_button_view.view.*
class NessieButton : LinearLayout {
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(attrs)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(attrs)
}
constructor(context: Context) : super(context) {
init(null)
}
enum class Style(
#DrawableRes
val backgroundRes: Int,
#ColorRes
val textColor: Int
) {
PRIMARY(
backgroundRes = R.drawable.nessie_button_style_primary,
textColor = R.color.nessie_button_style_primary_text_color
),
SECONDARY(
backgroundRes = R.drawable.nessie_button_style_secondary,
textColor = R.color.nessie_button_style_secondary_text_color
),
TERTIARY(
backgroundRes = R.drawable.nessie_button_style_tertiary,
textColor = R.color.nessie_button_style_tertiary_text_color
),
DESTRUCTIVE(
backgroundRes = R.drawable.nessie_button_style_destructive,
textColor = R.color.nessie_button_style_destructive_text_color
),
BEYOND(
backgroundRes = R.drawable.nessie_button_style_beyond,
textColor = R.color.nessie_button_style_beyond_text_color
);
companion object {
fun from(index: Int) = values().getOrElse(index) { Style.PRIMARY }
}
}
enum class Size(
#DimenRes
val horizontalPadding: Int,
#DimenRes
val verticalPadding: Int,
#DimenRes
val textSize: Int
) {
SMALL(
horizontalPadding = R.dimen.nessie_default_size_3x,
verticalPadding = R.dimen.nessie_default_size_2x,
textSize = R.dimen.nessie_textSizeDetail
),
MEDIUM(
horizontalPadding = R.dimen.nessie_default_size_3x,
verticalPadding = R.dimen.nessie_default_size_2x,
textSize = R.dimen.nessie_textSizeAction
),
LARGE(
horizontalPadding = R.dimen.nessie_default_size_4x,
verticalPadding = R.dimen.nessie_default_size_3x,
textSize = R.dimen.nessie_textSizeAction
);
companion object {
fun from(index: Int) = values().getOrElse(index) { Size.LARGE }
}
}
var text: CharSequence?
set(value) {
nessie_button_text_view.text = value
nessie_button_text_view.isVisible = !value.isNullOrBlank()
}
get() = nessie_button_text_view.text
var icon: Icon? = null
set(value) {
field = value
when (value) {
null -> {
nessie_button_icon_view.isVisible = false
}
else -> {
nessie_button_icon_view.icon = value
nessie_button_icon_view.isVisible = true
}
}
}
var style: Style = Style.PRIMARY
set(value) {
field = value
setBackgroundResource(value.backgroundRes)
val color = ResourcesCompat.getColor(resources, value.textColor, null)
nessie_button_icon_view.iconColor = color
nessie_button_text_view.setTextColor(color)
}
var size: Size = Size.LARGE
set(value) {
field = value
val horizontalPadding = resources.getDimensionPixelSize(value.horizontalPadding)
val verticalPadding = resources.getDimensionPixelSize(value.verticalPadding)
setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding)
val fontSize = resources.getDimension(value.textSize)
nessie_button_text_view.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize)
nessie_button_icon_view.apply {
iconPixelSize = fontSize.toInt()
layoutParams.apply {
width = fontSize.toInt()
height = fontSize.toInt()
}
}
}
init {
init(null)
}
override fun setEnabled(enabled: Boolean) {
super.setEnabled(enabled)
super.setFocusable(enabled)
val colorStateList = ResourcesCompat.getColorStateList(resources, style.textColor, null)
val viewState = drawableState
val color = colorStateList!!.getColorForState(viewState, 0)
nessie_button_text_view.setTextColor(color)
nessie_button_icon_view.iconColor = color
}
private fun init(attrs: AttributeSet?) {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER
inflate(context, R.layout.nessie_button_view, this)
val styledAttributes = context.obtainStyledAttributes(attrs, R.styleable.nessie_NessieButton)
try {
val iconIndex = styledAttributes.getInteger(R.styleable.nessie_NessieButton_nessie_icon, -1)
icon = when (iconIndex) {
-1 -> null
else -> Icon.from(iconIndex)
}
text = styledAttributes.getString(R.styleable.nessie_NessieButton_android_text)
style = Style.from(styledAttributes.getInteger(R.styleable.nessie_NessieButton_nessie_buttonStyle, Style.PRIMARY.ordinal))
size = Size.from(styledAttributes.getInteger(R.styleable.nessie_NessieButton_nessie_buttonSize, Size.LARGE.ordinal))
isEnabled = styledAttributes.getBoolean(R.styleable.nessie_NessieButton_android_enabled, true)
} finally {
styledAttributes.recycle()
}
nessie_button_text_view.typeface = context.getFont(R.font.nessie_proximanova_bold)
}
override fun addView(child: View, index: Int, params: ViewGroup.LayoutParams?) {
if (child.id == R.id.nessie_button_icon_view || child.id == R.id.nessie_button_text_view) {
super.addView(child, index, params)
} else {
throw IllegalArgumentException("Cannot add more views to a NessieButton")
}
}
}
And this is the view layout:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/root_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:padding="#dimen/nessie_default_size_2x"
tools:background="#drawable/nessie_button_primary_background"
tools:parentTag="android.widget.LinearLayout">
<com.classdojo.android.nessie.icon.IconImageView
android:id="#+id/nessie_button_icon_view"
android:layout_width="#dimen/nessie_default_size_3x"
android:layout_height="#dimen/nessie_default_size_3x"
android:layout_marginEnd="#dimen/nessie_default_size" />
<TextView
android:id="#+id/nessie_button_text_view"
style="#style/nessie_action"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineHeight="22sp"
android:textStyle="bold"
tools:text="My button"
tools:textColor="#color/nessie_white" />
</merge>
It turns out that it wasn't related to the merge/custom view, but was related to the fact that the editor preview couldn't find the font resource.
Wrapping the instances where the font was loaded in if (!isInEditMode){} resolved the problem.
I knew there was an errors list, but I hadn't used it in a while and couldn't find it. In case someone comes across this question, it's the blue i icon in the top right which shows you the errors hit when rendering the view.
<merge is not a ViewGroup. Hence, the android:attributes on that tag are ignored. This means, that your view does not have an id, width, height, gravity nor does it have padding.
Either add the attributes to where you are using your custom view like so:
<com.classdojo.android.nessie.NessieButton
android:id="#+id/root_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:padding="#dimen/item_spacing_normal"/>
Or, if these attributes should be the same for all NessieButton's, set these properties programatically. Inside your init() methods sounds like the best place.
Be careful with the android:id as well! You probably do not want to set it programatically. But you will almost certainly want to set it, when you actually use your NessieButton.

How to animate TextView with Alpha from Left to Right?

I'm working on Android TextView animation.
Requirement is TextView is at fix location of the screen and every character should be animate with alpha (Lower to higher). I've tried couple of libraries unfortunately it doesn’t work for me.
Reference screenshot:
If anybody has solution for this, kindly provide it. Thanks
After doing lots of research on the same, I'm posting my own answer.
Steps:
Create CustomTextLayout
class CustomTextLayout #JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayoutCompat(context, attrs, defStyleAttr) {
private var characterAnimationTime = 100
private var textSize = 22f
private var letterSpacing = 0f
private var animationDuration = 2000L
init {
orientation = HORIZONTAL
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomTextLayout, defStyleAttr, 0)
textSize = typedArray.getFloat(R.styleable.CustomTextLayout_textSize, textSize)
typedArray.recycle()
}
/**
* This function sets the animated alpha text
* #param context Context of Activity / Fragment
* #param text Text string
* #param initialDelay Start animation delay
*/
fun setAnimatedText(context: Context, text: String, initialDelay: Long = 0) {
var textDrawPosition = 0
Handler().postDelayed({
for (char in text) {
val textView = getTextView(char.toString())
textView.visibility = View.GONE
this.addView(textView)
textDrawPosition++
drawAnimatedText(
context,
this,
textView,
textDrawPosition,
text,
(textDrawPosition * characterAnimationTime).toLong()
)
}
}, initialDelay)
}
private fun drawAnimatedText(
context: Context,
parentView: LinearLayoutCompat,
textView: AppCompatTextView,
position: Int,
text: String,
initialDelay: Long
) {
val colorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), Color.WHITE, Color.BLACK)
colorAnimation.startDelay = initialDelay
colorAnimation.duration = animationDuration
colorAnimation.addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animator: Animator) {
textView.visibility = View.VISIBLE
}
override fun onAnimationEnd(animator: Animator) {
if (position == text.length) {
val updatedTextView = getTextView(text)
updatedTextView.setTextColor(Color.BLACK)
updatedTextView.visibility = View.VISIBLE
parentView.removeAllViews()
parentView.addView(updatedTextView)
}
}
override fun onAnimationCancel(animator: Animator) {
}
override fun onAnimationRepeat(animator: Animator) {
}
})
colorAnimation.addUpdateListener {
textView.setTextColor(it.animatedValue as Int)
}
colorAnimation.start()
}
private fun getTextView(text: String): AppCompatTextView {
val textView = AppCompatTextView(context)
textView.text = text
textView.textSize = textSize
textView.setTypeface(Typeface.SANS_SERIF, Typeface.ITALIC)
textView.letterSpacing = letterSpacing
return textView
}
Add in layout file
<com.mypackagename.CustomTextLayout
app:textSize="30"
app:letterSpacing="0.1"
android:id="#+id/textLayoutFirst"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</com.mypackagename.CustomTextLayout>
Add attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomTextLayout">
<attr name="textSize" format="float"/>
<attr name="letterSpacing" format="float"/>
</declare-styleable>
</resources>
Start animation:
textLayoutFirst.setAnimatedText(this, "Some text here")
It's done.

How to make error message in TextInputLayout appear in center

Currently it looks as in attached with this layout:
<android.support.design.widget.TextInputLayout
android:id="#+id/layoutCurrentPW"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
app:errorEnabled="true">
How to set the error message "password must at least be 8 characters" to center gravity ?
I tried with android:gravity="center" but that did not work.
EDIT
Layout that includes EditText:
<android.support.design.widget.TextInputLayout
android:id="#+id/layoutCurrentPW"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
app:errorEnabled="true">
<EditText
android:id="#+id/editTextCurrentPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:gravity="center"
android:hint="#string/current_password"
android:inputType="textPassword"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/black" />
</android.support.design.widget.TextInputLayout>
I wanted to know if there is any way to handle it from framework..seems no.
But the way TextInputLayout work is:
- hint will be shown on top of EditText when user touches it.
- Error messages will be shown just under the TextInputLayout and aligned to start.
I had 40dp of left_margin to my EditText due to which misalignment between hint and error message. So for now, I removed left_margin 40dp from EditText and applied same to TextInputLayout itself so it looks fine now.
Lesson learnt :-) is if any margins has to be applied to EditText, better same, if possible, can be applied to TextInputLayout to keep hint and error messages to be placed properly.
class CenterErrorTextInputLayout(context: Context, attrs: AttributeSet) : TextInputLayout(context, attrs) {
override fun setErrorTextAppearance(resId: Int) {
super.setErrorTextAppearance(resId)
val errorTextView = this.findViewById<TextView>(R.id.textinput_error)
val errorFrameLayout = errorTextView.parent as FrameLayout
errorTextView.gravity = Gravity.CENTER
errorFrameLayout.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
}}
Here a solution that always centers the errormessage no matter how big your TextInputLayout is.
You make a own class that inherits from TextInputLayout. Then override the ShowError(string text, Drawable icon) method. If the error is called you center the textView with the error.
public class TextInputLayout_Center : TextInputLayout
{
public override void ShowError(string text, Android.Graphics.Drawables.Drawable icon)
{
base.ShowError(text, icon);
centerErrorMessage(this);
}
void centerErrorMessage(ViewGroup view)
{
for (int i = 0; i < view.ChildCount; i++)
{
View v = view.GetChildAt(i);
if (v.GetType() == typeof(TextView))
{
v.LayoutParameters = new LayoutParams(ViewGroup.LayoutParams.MatchParent, v.LayoutParameters.Height);
((TextView)v).Gravity = GravityFlags.CenterHorizontal;
((TextView)v).TextAlignment = TextAlignment.Center;
}
if (v is ViewGroup)
{
centerErrorMessage((ViewGroup)v);
}
}
}
}
I achieved it by setting start margin for the error view. Below you can see my overriden version of setError method of the TextInputLayout component.
#Override
public void setError(#Nullable CharSequence errorText) {
// allow android component to create error view
if (errorText == null) {
return;
}
super.setError(errorText);
// find this error view and calculate start margin to make it look like centered
final TextView errorTextInput = (TextView) findViewById(R.id.textinput_error);
errorTextInput.measure(0, 0);
int errorWidth = errorTextInput.getMeasuredWidth();
int layoutWidth = getWidth();
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) errorTextInput.getLayoutParams();
params.setMarginStart((layoutWidth - errorWidth) / 2);
errorTextInput.setLayoutParams(params);
}
#Override
public void setErrorEnabled(boolean enabled) {
super.setErrorEnabled(enabled);
if (!enabled)
return;
try {
setErrorGravity(this);
} catch (Exception e) {
e.printStackTrace();
}
}
private void setErrorGravity(ViewGroup view) throws Exception {
for (int i = 0; i < view.getChildCount(); i++) {
View errorView = view.getChildAt(i);
if (errorView instanceof TextView) {
if (errorView.getId() == com.google.android.material.R.id.textinput_error) {
FrameLayout errorViewParent = (FrameLayout) errorView.getParent();
errorViewParent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
((TextView) errorView).setGravity(Gravity.RIGHT);
((TextView) errorView).setTypeface(FontUtils.getTypeFace(view.getContext(), FontUtils.FONT_NAZANIN_TAR));
}
}
if (errorView instanceof ViewGroup) {
setErrorGravity((ViewGroup) errorView);
}
}
}
Hi if you using last version of material design (v 1.2 and above), you have to use this way: (I set gravity to end for support rtl)
Thanks #Emmanuel Guerra
class MyTextInputLayout : TextInputLayout {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttrs: Int) : super(context, attrs, defStyleAttrs)
override fun setErrorEnabled(enabled: Boolean) {
super.setErrorEnabled(enabled)
if (!enabled) {
return
}
try {
changeTextAlignment(com.google.android.material.R.id.textinput_error, View.TEXT_ALIGNMENT_VIEW_END)
val errorView: ViewGroup = this.getChildAt(1) as LinearLayout
val params: LinearLayout.LayoutParams = errorView.layoutParams as LinearLayout.LayoutParams
params.gravity = Gravity.END
errorView.layoutParams = params
//errorView.setPadding(0, 0, 0, 0) //use this to remove error text padding
//setErrorIconDrawable(0)
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun changeTextAlignment(textViewId: Int, alignment: Int) {
val textView = findViewById<TextView>(textViewId)
textView.textAlignment = alignment
}
}
A custom TextInputLayout class for for aligning the error text.
class CenterErrorTextInputLayout #JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : TextInputLayout(context, attrs, defStyleAttr) {
override fun setErrorEnabled(enabled: Boolean) {
super.setErrorEnabled(enabled)
if (!enabled) return
try {
setErrorTextAlignment()
} catch (e: Exception) {
Timber.e(e, "Failed to set error text : RightErrorTextInputLayout")
}
}
private fun setErrorTextAlignment() {
val errorView: TextView = this.findViewById(R.id.textinput_error)
errorView.textAlignment = View.TEXT_ALIGNMENT_CENTER
}
}
To align the text to the end, use View.TEXT_ALIGNMENT_VIEW_END instead.

Categories

Resources