I have a TextInputLayout
with a custom Style that needs to be heavily reused so I am trying to turn it into a custom view.
Here is xml to be reused :
<com.google.android.material.textfield.TextInputLayout
style="@style/TextInputLayoutAppearance"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
TextInputLayoutAppearance
is the custom style I have created in the styles.xml
Here is the Class for my custom view :
class OutlinedTextInput @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : TextInputLayout(context, attrs, defStyleAttr) {
init {
LayoutInflater.from(context).inflate(R.layout.view_outlined_textinput, this, true)
}
}
Here is the view_outlined_textinput
I have adapted from the original xml above, for the custom view :
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:parentTag="com.google.android.material.textfield.TextInputLayout">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</merge>
There are 2 things to notice here :
The layout uses a merge tag to avoid redundant view in the view hierarchy.
It is crucial to apply the custom style. The style is applied in the original xml using style= syntax. However, since the merge tag is being used for the custom view it cannot be done that way.
I tried setting the style as follows but it didn't work :
class OutlinedTextInput @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.style.TextInputLayoutAppearance
) : TextInputLayout(context, attrs, defStyleAttr) {
I assume the above solution should work as the 3rd parameter in the constructor is to pass in the style.
Another option is to set all the properties programatically in the init {}
of my custom view but that defeats the purpose of having declared a style in the Styles file.
What are my options ?