Я создаю CustomView, который в основном охватывает TextInputLayout
и TextInputEditText
.Редактор макетов в Android Studio не может отобразить предварительный просмотр этого пользовательского представления.Я попытался создать проект, очистил его и все, он все еще не будет отображать предварительный просмотр.Вот файл Kotlin для того же.
class PrimaryEditText : LinearLayout {
private var textInputLayout: TextInputLayout
private var textInputEditText: TextInputEditText
private var onTextChangeListener: ((String) -> Unit)? = null
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, attrs: AttributeSet) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
val inflater = LayoutInflater.from(context)
val rootView = inflater.inflate(R.layout.primary_edit_text, this)
textInputLayout = rootView.findViewById(R.id.textInputLayout)
textInputEditText = rootView.findViewById(R.id.textInputEditText)
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.PrimaryEditText)
initAttrs(typedArray)
typedArray.recycle()
// Add TextWatcher to listen to text
textInputEditText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onTextChangeListener?.invoke(s?.toString() ?: "")
}
})
}
/*
* Initialize the attributes
* */
private fun initAttrs(typedArray: TypedArray) {
val inputType = typedArray.getInteger(R.styleable.PrimaryEditText_android_inputType, InputType.TYPE_CLASS_TEXT)
textInputEditText.inputType = inputType
textInputLayout.hint = typedArray.getString(R.styleable.PrimaryEditText_hint)
}
/**
* Set and get the text entered by the user
* */
var inputText: String
get() = textInputEditText.text.toString()
set(value) {
textInputEditText.setText(value)
}
/**
* Set and get the error on TextInputLayout
* */
var error: String
get() = textInputLayout.error.toString()
set(value) {
textInputLayout.error = value
}
/**
* Add a listener for text change
* */
fun setOnTextChangeListener(listener: (String) -> Unit) {
this.onTextChangeListener = listener
}
}
Вот файл макета:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/textInputEditText"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:hint="Testing" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>