Following code sample demonstrates to set maxLength limit for text in Custom view EditText.
This restrict the user to enter max 30 chars in CustomView component .
main_activity.xml :
<com.view.ViewCustomComponent
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapWords"
app:title="Address"
app:required="false"
app:hint="Address"
app:maxlength="30"/>
attributes.xml :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="title" format="string" />
<attr name="required" format="boolean" />
<attr name="hint" format="string" />
<attr name="text" format="string" />
<attr name="lines" format="integer" />
<attr name="maxlength" format="integer" />
<declare-styleable name="FormEditTextComponent">
<attr name="title" />
<attr name="required" />
<attr name="hint" />
<attr name="text" />
<attr name="lines" />
<attr name="maxlength" />
<attr name="android:inputType" />
</declare-styleable>
</resources>
ViewCustomComponent.kt :
class ViewCustomComponent : LinearLayout, IBaseFormComponent {
private fun initialize(context: Context, attributeSet: AttributeSet? = null) {
attributeSet?.let {
val title = typedArray.getString(R.styleable.FormEditTextComponent_title)
val text = typedArray.getString(R.styleable.FormEditTextComponent_text)
val placeholder = typedArray.getString(R.styleable.FormEditTextComponent_hint)
val lines = typedArray.getInt(R.styleable.FormEditTextComponent_lines, 0)
val maxlength = typedArray.getInt(R.styleable.FormEditTextComponent_maxlength , 0)
component_title.text = title
component_text.setText(text, TextView.BufferType.NORMAL)
component_text.hint = placeholder
component_text.inputType = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
/**
* This CustomView used by many views and here the condition to set maxlength=50 only for
* address1 , address2 , city of EmergencyProfile and no impact for other views
*/
if(maxlength == 50) {
component_text.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(maxlength))
} else {
component_text.filters = arrayOf(InputEmojiFilter())
}
}
}
}