Подтвердить что ты не робот

Отжимать содержимое, кроме некоторого вида, когда отображается клавиатура

У меня есть макет, содержащий 5 EditText и Button и TextView внизу. Теперь, когда я нажимаю EditText, клавиатура будет показана, а все мой View будет нажат.

Теперь я не хочу нажимать клавиши TextView и Button на клавиатуру выше, просто хочу отжать все EditText внутри ScrollView до клавиатуры выше.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#ff0"
        >

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

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 1"

                />

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 2"
                />

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 3"
                />

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 4"
                />

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 5"
                android:inputType="textNoSuggestions"
                />

        </LinearLayout>

    </ScrollView>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Button"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:text="I don't want to push this TextView and Button to above keyboard when keyboard is shown. Just obly want to push the ScrollView that contain all EditText"
        />
</LinearLayout>

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

У меня есть идея. Когда я слушаю, когда клавиатура показывается и скрывается. При показе клавиатуры я устанавливаю нижнее поле ScrollView = высота клавиатуры, когда клавиатура скрывается, я задаю этот край = 0.
Есть ли способ справиться с моим делом? Любая помощь или предложение были бы очень оценены.

UPDATE
Если я использую windowSoftInputMode=adjustPan = > не все EditText нажатие на клавиатуру выше

Если я использую windowSoftInputMode=adjustResize = > Button, TextView и все EditText нажимают вверх до клавиатуры

4b9b3361

Ответ 1

Не будет работать - нет надежного API для обнаружения, когда отображается клавиатура. Вы увидите "решения" на этом сайте, но у них есть ложные срабатывания и негативы. Но для вас лучше всего установить softInputMode для настройкиPan. Это заставит ОС прокрутить весь экран на минимальное количество, необходимое для того, чтобы курсор был виден над клавиатурой. (все приложение выходит за клавиатуру из-за режима adjustResize).

Ответ 2

  • Протестировано на всех мобильных и планшетных устройствах Nexus. Он работает нормально. Я использую ваш XML-код макета и добавил только представления к представлениям.

  • Я использую приведенную ниже библиотеку в своем производственном приложении, и это очень перспективно. Чтобы добиться того же и добавить строку ниже в app gradle: 'Net.yslibrary.keyboardvisibilityevent: keyboardvisibilityevent: 2.0.1' Вот ссылка для того же.

  • Обратитесь к приведенному ниже пояснению для остальной части кода: Код манифеста, код операции, код макета деятельности.

Ответ 3

Вы должны добавить android:windowSoftInputMode="adjustPan" в свой Manifest, и он будет работать как Pro:

<activity android:name=".your_activity_name"
        android:windowSoftInputMode="adjustPan">
    ..............

</activity>

Ответ 4

Попробуйте добавить этот макет,

 <LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/activity_main"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical">
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:background="#ff0"
    >

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

        <EditText
            android:layout_marginTop="30dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="EditText 1"

            />

        <EditText
            android:layout_marginTop="30dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="EditText 2"
            />

        <EditText
            android:layout_marginTop="30dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="EditText 3"
            />

        <EditText
            android:layout_marginTop="30dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="EditText 4"
            />

        <EditText
            android:layout_marginTop="30dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="EditText 5"
            android:inputType="textNoSuggestions"
            />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="Button"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000"
            android:text="any text"
        />
    </LinearLayout>
  </ScrollView>


</LinearLayout>

Ответ 5

Дать id всем редактируемым текстам, кнопкам и текстовым изображениям: -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#ff0">

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

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 1"
                android:id="@+id/et1"
                />

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 2"
                android:id="@+id/et2"/>

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 3"
                android:id="@+id/et3"/>

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 4"
                android:id="@+id/et4"/>

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 5"
                android:inputType="textNoSuggestions"
                android:id="@+id/et5"/>

        </LinearLayout>

    </ScrollView>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Button"
        android:id="@+id/btn"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:text="I don't want to push this TextView and Button to above keyboard when keyboard is shown. Just obly want to push the ScrollView that contain all EditText"
        android:id="@+id/tv"/>
</LinearLayout>

В вашем манифесте: -

android:windowSoftInputMode="adjustResize|stateHidden"

В вашей деятельности: -

public class Main2Activity extends AppCompatActivity {
    EditText e1,e2,e3,e4,e5;
    Button button;
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        e1=(EditText)findViewById(R.id.et1);
        e2=(EditText)findViewById(R.id.et2);
        e3=(EditText)findViewById(R.id.et3);
        e4=(EditText)findViewById(R.id.et4);
        e5=(EditText)findViewById(R.id.et5);
        textView=(TextView)findViewById(R.id.tv);
        button=(Button)findViewById(R.id.btn);
        e1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                hideKeyBoard();
            }
        });
        e2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                hideKeyBoard();
            }
        });
        e3.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                hideKeyBoard();
            }
        });
        e4.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                hideKeyBoard();
            }
        });
        e5.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                hideKeyBoard();
            }
        });

    }
    private void hideKeyBoard(){
        final View activityRootView = findViewById(R.id.activity_main);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
                if (heightDiff > dpToPx(Main2Activity.this, 200)) { // if more than 200 dp, it probably a keyboard...
                    // ... do something here
                    button.setVisibility(View.GONE);
                    textView.setVisibility(View.GONE);
                }
                else {
                    button.setVisibility(View.VISIBLE);
                    textView.setVisibility(View.VISIBLE);
                }
            }
        });
    }
    public static float dpToPx(Context context, float valueInDp) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
    }

}

Здесь я проверяю, отображается ли клавиатура или нет. И если это видно, скрывая кнопку и текстовое изображение.

Ответ 6

Используйте Relavtive Layout как родительский с двумя Linear Layout как дочерний элемент и поместите scrollview в первый LinearLayout, а кнопка с текстовым видом в другом.

Используйте этот код. Протестируйте его, будете работать так, как вы ожидаете.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#ff0"
        >

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

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 1"

                />

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 2"
                />

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 3"
                />

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 4"
                />

            <EditText
                android:layout_marginTop="30dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="EditText 5"
                android:inputType="textNoSuggestions"
                />

        </LinearLayout>

    </ScrollView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_below="@id/linear">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="Button"
            />
        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000"
            android:text="I don't want to push this TextView and Button above keyboard"
            />
    </LinearLayout>
</RelativeLayout>

Ответ 7

первый макет изменения

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#ff0">

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

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="30dp"
                android:hint="EditText 1"

                />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="30dp"
                android:hint="EditText 2" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="30dp"
                android:hint="EditText 3" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="30dp"
                android:hint="EditText 4" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="30dp"
                android:hint="EditText 5"
                android:inputType="textNoSuggestions" />

        </LinearLayout>

    </ScrollView>


    <RelativeLayout
        android:id="@+id/rlBtm"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Button" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn"
            android:text="I don't want to push this TextView and Button to above keyboard when keyboard is shown. Just obly want to push the ScrollView that contain all EditText"
            android:textColor="#000" />

    </RelativeLayout>

</LinearLayout>

затем добавьте класс

public class KeyboardUtil {

    public static void setKeyboardVisibilityListener(Activity activity, final KeyboardVisibilityListener keyboardVisibilityListener) {
        final View contentView = activity.findViewById(android.R.id.content);
        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            private int mPreviousHeight;

            @Override
            public void onGlobalLayout() {
                int newHeight = contentView.getHeight();
                if (mPreviousHeight != 0) {
                    if (mPreviousHeight > newHeight) {
                        // Height decreased: keyboard was shown
                        keyboardVisibilityListener.onKeyboardVisibilityChanged(true);
                    } else if (mPreviousHeight < newHeight) {
                        // Height increased: keyboard was hidden
                        keyboardVisibilityListener.onKeyboardVisibilityChanged(false);
                    } else {
                        // No change
                    }
                }
                mPreviousHeight = newHeight;
            }
        });
    }
}

И из действий onCreate

KeyboardUtil.setKeyboardVisibilityListener(this, new KeyboardVisibilityListener() {
            @Override
            public void onKeyboardVisibilityChanged(boolean keyboardVisible) {
                rlBtm.setVisibility(keyboardVisible ? View.GONE : View.VISIBLE);
            }
        });

найти id для rlBtm.

Ответ 8

вы можете использовать код ниже (но в этом случае ваша кнопка и ваше текстовое изображение были в конце экрана, иначе вы можете управлять им также с помощью линейного макета. Если вы хотите, чтобы кнопка и текст отображались, тогда спросите PLS.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
    android:id="@+id/sw1"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:id="@+id/ll1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="100dp"
            android:background="#ff009988"
            android:padding="10dp"
            android:textColor="#ffffff" />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:layout_marginBottom="10dp"
            android:background="#ff009988"
            android:padding="10dp"
            android:textColor="#ffffff" />
 <RelativeLayout
    android:id="@+id/btmbar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true">

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button2"
        android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, " />
</RelativeLayout>
    </LinearLayout>
</ScrollView>