我正在使用自定义editText,并且一开始就受到迷恋。这也破坏了我在xml设计页面上的约束。默认情况下,一切正常。
自定义EditText的代码:使用它将光标锁定在最后。
class CustomEditText(context: Context) : EditText(context) {
public override fun onSelectionChanged(start: Int, end: Int) {
val text = text
if (text != null) {
if (start != text.length || end != text.length) {
setSelection(text.length, text.length)
return
}
}
super.onSelectionChanged(start, end)
}
}
xml中的代码:
<sh1gure.test.creditcardform.view.CustomEditText
android:id="@+id/etCardDate"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginEnd="8dp"
android:background="@drawable/edit_text_back"
android:ems="10"
android:hint="@string/mm_yy"
android:inputType="number"
android:maxLength="@integer/max_length_date"
android:paddingLeft="8dp"
android:paddingRight="8dp"
app:layout_constraintBottom_toTopOf="@+id/btn_add_card"
app:layout_constraintEnd_toStartOf="@+id/etCardCvv"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="@+id/etCardNumber1"
app:layout_constraintTop_toBottomOf="@+id/textView3" />
Logcat:
Process: sh1gure.test.creditcardform, PID: 24143
java.lang.RuntimeException: Unable to start activity ComponentInfo{sh1gure.test.creditcardform/sh1gure.test.creditcardform.view.MainActivity}: android.view.InflateException: Binary XML file line #53: Binary XML file line #53: Error inflating class sh1gure.test.creditcardform.view.CustomEditText
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2925)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3060)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1818)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6762)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: android.view.InflateException: Binary XML file line #53: Binary XML file line #53: Error inflating class sh1gure.test.creditcardform.view.CustomEditText
Caused by: android.view.InflateException: Binary XML file line #53: Error inflating class sh1gure.test.creditcardform.view.CustomEditText
答案 0 :(得分:0)
对于XML膨胀,必须为构造函数提供一个AttributeSet
作为第二个参数:
class CustomEditText(context: Context, attrs: AttributeSet? = null) : EditText(context, attrs) {
public override fun onSelectionChanged(start: Int, end: Int) {
val text = text
if (text != null) {
if (start != text.length || end != text.length) {
setSelection(text.length, text.length)
return
}
}
super.onSelectionChanged(start, end)
}
}