首页 > 解决方案 > Android:将 TextInputLayout 设为只读

问题描述

如何将 a 设置TextInputLayout为只读?

我的代码如下所示:

<com.google.android.material.textfield.TextInputLayout
        android:id="@+id/TextInputLayout_fromAddAbsenceBottomSheet_AbsenceTaken"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:hint="Absence Taken"
        app:helperText="* Optional"
        app:layout_constraintEnd_toEndOf="@+id/TextInputLayout_fromAddAbsenceBottomSheet_AbsenceGiven"
        app:layout_constraintStart_toStartOf="@+id/TextInputLayout_fromAddAbsenceBottomSheet_AbsenceGiven"
        app:layout_constraintTop_toBottomOf="@+id/TextInputLayout_fromAddAbsenceBottomSheet_AbsenceGiven"
        style="@style/Widget.Unify.TextInputLayout">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/TextField_fromAddAbsenceBottomSheet_AbsenceTaken"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="numberDecimal"
            style="@style/Widget.Unify.EditText"/>

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

我需要使TextInputLayout只读不是EditText

我需要使它只在TextInputLayout级别上读取,因为我需要对其应用样式。

我已经尝试过android:enabled="false"TextInputLayout但它仍然可以让我更改文本。

标签: androidandroid-stylesandroid-textinputlayoutmaterial-componentsmaterial-components-android

解决方案


问题不清楚。

要禁用TextInputLayoutjust 使用:

    <com.google.android.material.textfield.TextInputLayout
        android:enabled="false" 
        ..>

它适用于版本 1.1.0(当前1.1.0-beta02)和 1.2.0(当前1.2.0-alpha02)。
结果:启用/禁用:

在此处输入图像描述 在此处输入图像描述

您可以使用 和 选择器自定义框颜色app:boxStrokeColor
就像是:

    <com.google.android.material.textfield.TextInputLayout
        android:enabled="false" 
        app:boxStrokeColor="@color/text_input_layout_stroke_color"
        ..>

选择器在哪里:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="..." android:state_focused="true"/>
  <item android:alpha="0.87" android:color="..." android:state_hovered="true"/>
  <item android:alpha="0.12" android:color="..." android:state_enabled="false"/>
  <item android:color="..."/>
</selector>

其中在禁用状态下使用的颜色由 定义<item android:alpha="0.12" android:color="..." android:state_enabled="false"/>

结果:使用不同的 boxStrokeColor 禁用。

在此处输入图像描述

如果要自定义 EditText 的颜色,可以使用该android:textColor属性:

        <com.google.android.material.textfield.TextInputEditText
            android:textColor="@color/..."

结果:使用不同的编辑文本颜色禁用。

在此处输入图像描述

同样在这种情况下,您可以使用选择器:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:color="@color/..."/>
  <item android:color="@color/...."/>
</selector>

推荐阅读