Непрозрачный фон в плавающей подсказке в TextInputLayout

Мне нужно сделать textinputlayout с плавающей меткой подсказки, которая должна иметь белый фон. Что-то похожее на это--

Ожидаемый дизайн:

Ожидается дизайн

Но все, что я смог сделать до сих пор, это:

Фактический дизайн с использованием TextInputLayout:

В настоящее время метка подсказки в TextInputLayout имеет прозрачный фон. Может ли кто-нибудь помочь мне и сказать, как сделать это возможным?

Вот мой код (макет texinput):

<android.support.design.widget.TextInputLayout
    android:id="@+id/til_login_info"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/text_input_layout_background"
    app:hintTextAppearance="@style/TextStyle.Small.Hint">

    <EditText
        android:id="@+id/login_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/transparent"
        android:gravity="center_vertical"
        android:hint="Email / Mobile"
        android:inputType="text"
        android:textSize="14sp" />
</android.support.design.widget.TextInputLayout>

И фон, который я использую

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:gravity="bottom"
        android:top="5dp">
        <shape android:shape="rectangle">
            <stroke

                android:width="1px"
                android:color="@color/Grey300" />
            <corners android:radius="100dp" />
            <solid android:color="@color/transparent" />
        </shape>
    </item>
</layer-list>

Заранее спасибо!


person anup1912    schedule 18.03.2017    source источник
comment
Не могли бы вы поделиться своим кодом?   -  person Rafi Kamal    schedule 18.03.2017
comment
@RafiKamal Я добавил код, который использую   -  person anup1912    schedule 18.03.2017
comment
Попробуйте colorSurface в основном приложении. stackoverflow.com/questions/54002965/   -  person Igor    schedule 27.05.2020


Ответы (2)


Вы должны использовать стиль Material Design для Outline Box. Проще говоря:

style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"

к вашему TextInputLayout.

Для закругленных углов используйте:

boxCornerRadiusTopStart
boxCornerRadiusTopEnd
boxCornerRadiusBottomStart
boxCornerRadiusBottomEnd

См. Текстовое поле для Android в Руководстве по дизайну материалов введите здесь описание изображения

person Francis    schedule 03.09.2018
comment
У меня была такая же проблема, после того, как я применил этот стиль, моя подсказка не отображается. Есть ли разница со стилем контура и стилем заполненного поля? - person Menma; 24.09.2018
comment
@Menma намекнул на TextInputLayout вместо TextInputEditText - person Francis; 24.09.2018
comment
Я поставил подсказку andstyle="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox" на TextInputLayout, но после того, как я поставил этот стиль, моя подсказка не отображается. если я использую стиль по умолчанию, моя подсказка показывает - person Menma; 24.09.2018
comment
Без кода не знаю. style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox" хорошо работает? - person Francis; 24.09.2018
comment
Да... этот стиль работает хорошо, я понятия не имею, почему в стиле OutlinedBox подсказка не отображается - person Menma; 24.09.2018

Вот обходной путь:

1. Создайте структуру layout, как показано ниже:

activity_test.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:background="@android:color/white">

    <!-- Mobile number -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <View
            android:layout_width="match_parent"
            android:layout_height="52dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/bg_rounded_input_field" />

        <TextView
            android:id="@+id/text_dummy_hint_mobile_number"
            android:layout_width="wrap_content"
            android:layout_height="2dp"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="28dp"
            android:paddingLeft="4dp"
            android:paddingRight="4dp"
            android:text="Mobile Number"
            android:textSize="16sp"
            android:background="@android:color/white"
            android:visibility="invisible"/>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="28dp"
            android:layout_marginRight="28dp"
            android:hint="Mobile Number"
            android:textColorHint="@android:color/black"
            app:hintTextAppearance="@style/HintTextStyle">

            <EditText
                android:id="@+id/edit_mobile_number"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:maxLines="1"
                android:backgroundTint="@android:color/transparent"/>
        </android.support.design.widget.TextInputLayout>
    </RelativeLayout>

    <!-- Promo code -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp">

        <View
            android:layout_width="match_parent"
            android:layout_height="52dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/bg_rounded_input_field" />

        <TextView
            android:id="@+id/text_dummy_hint_promo_code"
            android:layout_width="wrap_content"
            android:layout_height="2dp"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="28dp"
            android:paddingLeft="4dp"
            android:paddingRight="4dp"
            android:text="Promo Code"
            android:textSize="16sp"
            android:background="@android:color/white"
            android:visibility="invisible"/>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="28dp"
            android:layout_marginRight="28dp"
            android:hint="Promo Code"
            android:textColorHint="@android:color/black"
            app:hintTextAppearance="@style/HintTextStyle">

            <EditText
                android:id="@+id/edit_promo_code"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:maxLines="1"
                android:backgroundTint="@android:color/transparent"/>
        </android.support.design.widget.TextInputLayout>
    </RelativeLayout>
</LinearLayout>

2. Используйте рисуемый ниже bg_rounded_input_field.xml для закругленных углов.

res/drawable/bg_rounded_input_field.xml

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

    <stroke
        android:color="@android:color/black"
        android:width="2dp">
    </stroke>

    <corners
        android:radius="1000dp">
    </corners>

</shape>

3. Используйте от HintTextStyle до TextInputLayout ниже, добавив атрибут app:hintTextAppearance="@style/HintTextStyle".

res/values/styles.xml

<style name="HintTextStyle" parent="TextAppearance.Design.Hint">
    <item name="android:textSize">16sp</item>
</style>

4. Наконец, в вашем Activity только show/hide text_dummy_hint_mobile_number и text_dummy_hint_promo_code во время focus меняются.

К вашему сведению, я использовал Handler с задержкой 100 millis, чтобы показать фиктивные подсказки TextView для синхронизации с TextInputLayout текстом подсказки animation.

TestActivity.java

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class TestActivity extends AppCompatActivity {

    TextView textDummyHintMobileNumber;
    TextView textDummyHintPromoCode;
    EditText editMobileNumber;
    EditText editPromoCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        textDummyHintMobileNumber = (TextView) findViewById(R.id.text_dummy_hint_mobile_number);
        textDummyHintPromoCode = (TextView) findViewById(R.id.text_dummy_hint_promo_code);
        editMobileNumber = (EditText) findViewById(R.id.edit_mobile_number);
        editPromoCode = (EditText) findViewById(R.id.edit_promo_code);

        // Mobile number
        editMobileNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (hasFocus) {
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // Show white background behind floating label
                            textDummyHintMobileNumber.setVisibility(View.VISIBLE);
                        }
                    }, 100);
                } else {
                    // Required to show/hide white background behind floating label during focus change
                    if (editMobileNumber.getText().length() > 0)
                        textDummyHintMobileNumber.setVisibility(View.VISIBLE);
                    else
                        textDummyHintMobileNumber.setVisibility(View.INVISIBLE);
                }
            }
        });

        // Promo code
        editPromoCode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (hasFocus) {
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // Show white background behind floating label
                            textDummyHintPromoCode.setVisibility(View.VISIBLE);
                        }
                    }, 100);
                } else {
                    // Required to show/hide white background behind floating label during focus change
                    if (editPromoCode.getText().length() > 0)
                        textDummyHintPromoCode.setVisibility(View.VISIBLE);
                    else
                        textDummyHintPromoCode.setVisibility(View.INVISIBLE);
                }
            }
        });
    }
}

ВЫВОД:

введите описание изображения здесь

Надеюсь, это поможет~

person Ferdous Ahamed    schedule 10.07.2017