如何从自定义视图中的textInputEditText获取输入文本?AndroidKotlin

lokaqttq  于 2023-02-24  发布在  Kotlin
关注(0)|答案(1)|浏览(165)

这是我的自定义视图:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

       <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/textInputLayout"
            style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.Dense"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="40dp"
            app:boxBackgroundColor="#E6DEDE"
            app:boxStrokeColor="@color/black"
            app:boxStrokeWidth="1dp"
            app:boxStrokeWidthFocused="2dp"

            app:hintTextColor="@color/black">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/textInputEditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:inputType="textEmailAddress"
                android:textColor="@color/black"
                android:textSize="18sp" />

        </com.google.android.material.textfield.TextInputLayout>

   </LinearLayout>

    </merge>

这是自定义视图类:

@SuppressLint("MissingInflatedId")
class CustomEditText(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) {

    private val textInputLayout: TextInputLayout
    private val editText: TextInputEditText

    init {
        val view = inflate(context, R.layout.custom_edit_text, this)
        textInputLayout = view.findViewById(R.id.textInputLayout)
        editText = view.findViewById(R.id.textInputEditText)
    }

    fun getEditText():TextInputEditText
    {
        return findViewById(R.id.textInputEditText)
    }

    fun setHint(hint: String){
        editText.hint = hint
    }

    fun getText() : String {
        return getEditText().text.toString()
    }
}

@BindingAdapter("hint")
fun setCustomHint(editText: CustomEditText,hint: String?) {
    if (hint != null) {
        editText.setHint(hint)
    }
    }

这是我使用这个函数的片段代码:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val username = binding.etUsername.getTextText()
        binding.btnSignUp.setOnClickListener {
            Toast.makeText(context, username, Toast.LENGTH_SHORT).show()
        }

  }

我尝试从自定义编辑文本中获取文本,但它返回null -(“”)。我在片段中使用自定义视图。我想从片段中的自定义视图的编辑文本中获取输入。

j2qf4p5b

j2qf4p5b1#

使用

fun getEditText():TextInputEditText
    {
        return editText
   }

或以getTextFunction为单位

fun getText() : String {
    return editText.text.toString()
}

相关问题