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.
Related
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.
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.
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.
Is there any way to specify the input method type for android.support.v7.preference.EditTextPreference?
If you don't want to use a third party library, it is possible to specify a layout to the EditTextPreference
<EditTextPreference android:defaultValue="0"
android:key="some_key"
android:title="Title"
android:dialogLayout="#layout/preference_edit_text"/>
Then in res/layout/preference_edit_text.xml
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText android:id="#android:id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:singleLine="true"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginStart="21dp"
android:layout_marginEnd="21dp"/>
</android.support.constraint.ConstraintLayout>
Please note that the edit text id must be : #android:id/edit
but then you are free to use whatever you want inside the android:inputType field
I'm sure there's a better way to align the EditText rather than using 21dp margins
but at least it works
Now one can use Android-Support-Preference-V7-Fix library.Fixed EditTextPreference forwards the XML attributes (like inputType) to the EditText, just like the original preference did.
Here is my version of the answer from Cory Charlton, transfered to Jetpack preferences and written in Kotlin:
import android.content.Context
import android.content.SharedPreferences
import android.text.InputType
import android.util.AttributeSet
import androidx.preference.EditTextPreference
class EditIntegerPreference : EditTextPreference {
constructor(context: Context?) : super(context) {
setInputMethod()
}
constructor(context: Context?, attributeSet: AttributeSet?) : super(context, attributeSet) {
setInputMethod()
}
constructor(context: Context?, attributeSet: AttributeSet?, defStyle: Int) : super(
context,
attributeSet,
defStyle
) {
setInputMethod()
}
override fun getText(): String =
try {
java.lang.String.valueOf(sharedPreferences.getInt(key, 0))
} catch (e: Exception) {
"0"
}
override fun setText(text: String?) {
try {
if (text != null) {
sharedPreferences?.edit()?.putInt(key, text.toInt())?.apply()
summary = text
} else {
sharedPreferences?.remove(key)
summary = ""
}
} catch (e: Exception) {
sharedPreferences?.remove(key)
summary = ""
}
}
override fun onSetInitialValue(defaultValue: Any?) {
val defaultValueInt: Int =
when (defaultValue){
is Int -> defaultValue
is String -> try {defaultValue.toInt()} catch (ex: java.lang.Exception){0}
else -> 0
}
text = sharedPreferences.getInt(key, defaultValueInt).toString()
}
private fun setInputMethod() {
setOnBindEditTextListener {
it.inputType = InputType.TYPE_CLASS_NUMBER
}
}
fun SharedPreferences.remove(key: String) = edit().remove(key).apply()
}
Edit: The previous answers below were built on the stock android.preference.EditTextPreference and unfortunately don't work for the android.support.v7.preference.EditTextPreference.
In the android.preference.EditTextPreference the EditText control is created programmatically and the AttributeSet from the Preference is passed to it.
android.preference.EditTextPreference Source:
public EditTextPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
mEditText = new EditText(context, attrs);
// Give it an ID so it can be saved/restored
mEditText.setId(com.android.internal.R.id.edit);
/*
* The preference framework and view framework both have an 'enabled'
* attribute. Most likely, the 'enabled' specified in this XML is for
* the preference framework, but it was also given to the view framework.
* We reset the enabled state.
*/
mEditText.setEnabled(true);
}
White allows us to set the inputType on the Preference itself and have it pass through to the EditText. Unfortunately the android.support.v7.preference.EditTextPreference appears to create the EditText in the Layout
See this issue for ideas on working around this:
Just wanted to let you know that subclassing EditTextPreferenceDialogFragment and overriding onAddEditTextToDialogView as well as overriding PreferenceFragmentCompat#onDisplayPreferenceDialog to show that subclass as needed seems to be working fine, thanks for the help.
Create your own class that extends the EditTextPreference and set it there.
Here's my EditIntegerPreference class:
public class EditIntegerPreference extends EditTextPreference {
public EditIntegerPreference(Context context) {
super(context);
}
public EditIntegerPreference(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public EditIntegerPreference(Context context, AttributeSet attributeSet, int defStyle) {
super(context, attributeSet, defStyle);
getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
getEditText().setSelectAllOnFocus(true);
}
#Override
public String getText() {
try {
return String.valueOf(getSharedPreferences().getInt(getKey(), 0));
} catch (Exception e) {
return getSharedPreferences().getString(getKey(), "0");
}
}
#Override
public void setText(String text) {
try {
if (getSharedPreferences() != null) {
getSharedPreferences().edit().putInt(getKey(), Integer.parseInt(text)).commit();
}
} catch (Exception e) {
// TODO: This catch stinks!
}
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
getEditText().setSelectAllOnFocus(true);
if (restoreValue) {
getEditText().setText(getText());
} else {
super.onSetInitialValue(restoreValue, defaultValue != null ? defaultValue : "");
}
}
}
Note that it is possible to add the inputType attribute to the the EditTextPreference
android:inputType="number"
The reason I didn't go this route is that I wanted my preference to get stored as an Integer and not a String
Workaround for Kotlin + DataStore + androidx.Preference
Disclaimer!
Probably this isn't the way to do it!
Ideally one should only:
set the input to int
override in a DataStore class: putInt/getInt
Extension Function
In my case I had a PreferenceFragmentCompat, so:
fun PreferenceFragmentCompat.setNumericInput(
#StringRes prefRes: Int, initialValue: String) {
val preference = findPreference(getString(prefRes)) as EditTextPreference?
preference?.setOnBindEditTextListener { editText ->
editText.inputType = InputType.TYPE_CLASS_NUMBER or
InputType.TYPE_NUMBER_FLAG_SIGNED
// set the initial value: I read it from the DataStore and then
// pass it as the 2nd argument to setNumericInput.
// BTW, I do store stringPreferenceKeys, as it's the putString method
// that get's triggered
if (editText.text.isEmpty()) editText.setText(initialValue)
editText.setSelection(editText.text.length) // put cursor at the end
}
// to use it in the summary do something like:
preference?.setOnPreferenceChangeListener { it, newValue ->
it.summary = "updated: $newValue"
true
}
}
Also, in my Activity that extends BaseSettingsActivity I
replace the management from SharedPreferences using:
preferenceManager.preferenceDataStore = dataStoreCvLogger
Is there anyway to know when a progressbar has reached it maximum. Like a Listener then could plug into the ProgressBar and lets us know that the progress bar is at the maximum level ?
Kind Regards
There isn't a direct way to do this. A workaround could be to make a custom implementation of the ProgressBar and override the setProgress method:
public MyProgressBar extends ProgressBar
{
#Override
public void setProgress(int progress)
{
super.setProgress(progress);
if(progress == this.getMax())
{
//Do stuff when progress is max
}
}
}
I think the cleanest way would be just adding this to your code:
if (progressBar.getProgress() == progressBar.getMax()) {
// do stuff you need
}
If you need onProgressChanged like SeekBar - create custom progress (Kotlin):
class MyProgressBar : ProgressBar {
private var listener: OnMyProgressBarChangeListener? = null
fun setOnMyProgressBarChangeListener(l: OnMyProgressBarChangeListener) {
listener = l
}
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(
context,
attrs
)
constructor(
context: Context?,
attrs: AttributeSet?,
defStyleAttr: Int
) : super(context, attrs, defStyleAttr)
override fun setProgress(progress: Int) {
super.setProgress(progress)
listener?.onProgressChanged(this)
}
interface OnMyProgressBarChangeListener {
fun onProgressChanged(myProgressBar: MyProgressBar?)
}
}
And for example in your fragment:
progress_bar?.setOnMyProgressBarChangeListener(object :
MyProgressBar.OnMyProgressBarChangeListener {
override fun onProgressChanged(myProgressBar: MyProgressBar?) {
val p = progress_bar.progress
// do stuff like this
if (p != 100) {
percentCallback?.changePercent(p.toString()) // show animation custom view with grow percents
} else {
shieldView.setFinishAndDrawCheckMark() // draw check mark
}
}
})
I think overall you should never have to do this. Is there just one valid case where you need to listen to a progressbar progress? I mean, usually it's the other way around: you set the progressbar progress based on something, not the other way around, so you need to track the progress of that something instead of listening to a view (which may or may not exist by the way).