概要

右寄せしたEditTextの先頭に$マークなどをつける方法。
レイアウト
$マークの右に位置調整のためのスペースを配置するのがポイント。
activity=main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--$マークテキスト表示-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:text="$"
android:textColor="@color/black"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="@id/space"
app:layout_constraintEnd_toStartOf="@id/space"
app:layout_constraintTop_toTopOf="@id/space"
tools:ignore="SpUsage"/>
<!--$マーク位置調整のためのスペース-->
<View
android:id="@+id/space"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="@id/edit_text"
app:layout_constraintEnd_toEndOf="@id/edit_text"
app:layout_constraintTop_toTopOf="@id/edit_text"/>
<!--テキスト入力-->
<EditText
android:id="@+id/edit_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginHorizontal="20dp"
android:gravity="end"
android:importantForAutofill="no"
android:inputType="number"
android:textColor="@color/black"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="LabelFor"/>
</androidx.constraintlayout.widget.ConstraintLayout>
処理
テキストを入力する度に、レイアウトで配置したスペースのwidthを変更して$マークの位置を調整する。
MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.editText.addTextChangedListener(object : TextWatcher {
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
// $マーク位置をスペースで調整
val layoutParams = binding.space.layoutParams
layoutParams.width = Layout.getDesiredWidth(s, binding.editText.paint).toInt()
binding.space.layoutParams = layoutParams
}
override fun afterTextChanged(p0: Editable?) {}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
})
}