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

Android: изменение размера только частей изображения с помощью мягкой клавиатуры на экране

У меня есть представление с полем Edittext поверх ImageView. Когда клавиатура подходит, я хочу, чтобы окно изменялось, так что EditText больше не скрывается клавиатурой. В файле AndroidManifest я объявил android:windowSoftInputMode="adjustResize", и размер экрана изменился, но проблема в том, что я хочу, чтобы ImageView не изменялся. Как я могу сделать ImageView незатронутым?

Могу ли я надуть дополнительный макет только с помощью ImageView или изменит его размер? enter image description here

4b9b3361

Ответ 1

Полное решение включает в себя несколько ключевых моментов

  • Используйте RelativeLayout, так что Views можно настроить для перекрытия друг друга
  • Совместите EditText с нижней частью Windows с помощью android:layout_alignParentBottom="true"
  • Используйте android:windowSoftInputMode="adjustResize" в своем манифесте, чтобы нижняя часть Window изменилась, когда клавиатура всплывает (как вы упомянули)
  • Поместите ImageView внутри a ScrollView, чтобы ImageView мог быть больше, чем Window, и отключить прокрутку на ScrollView, используя ScrollView#setEnabled(false)

Вот файл макета

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.so3.MainActivity">
    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:src="@drawable/stickfigures"/>
    </ScrollView>
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@android:color/holo_blue_bright"
        android:text="Please enter text"
        android:textSize="40sp"
        android:gravity="center_horizontal"/>
</RelativeLayout>

Вот моя деятельность

package com.so3;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ScrollView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ScrollView sv = (ScrollView)findViewById(R.id.scroll);
        sv.setEnabled(false);
    }
}

Мой AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.so3" >
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.so3.MainActivity"
            android:windowSoftInputMode="adjustResize"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Снимки экрана моего решения

screenshot 1screenshot 2

Ответ 2

final View activityRootView = findViewById(R.id.mainScroll);

activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
        new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                int heightView = activityRootView.getHeight();
                int widthView = activityRootView.getWidth();
                if (1.0 * widthView / heightView > 1) {

                    Log.d("keyboarddddd      visible", "no");
                    relativeLayoutForImage.setVisibility(View.GONE);
                    relativeLayoutStatic.setVisibility(View.GONE);
                    //Make changes for Keyboard not visible


                } else {

                    Log.d("keyboarddddd      visible ", "yes");

                    relativeLayoutForImage.setVisibility(View.VISIBLE);
                    relativeLayoutStatic.setVisibility(View.VISIBLE);
                    //Make changes for keyboard visible


                }
            }
        });

Ответ 3

Для меня я не хотел предполагать, что высота клавиатуры - это определенное измерение. Что бы вы ни думали о создании onTouchListener, а затем выполните следующее:

    setOnTouchListener(new OnTouchListener()  {



        Runnable shifter=new Runnable(){
            public void run(){
                try {
                    int[] loc = new int[2];                 
                    //get the location of someview which gets stored in loc array
                    findViewById(R.id.someview).getLocationInWindow(loc);
                    //shift so user can see someview
                    myscrollView.scrollTo(loc[0], loc[1]);   
                }
                catch (Exception e) {
                    e.printStackTrace();
                }   
            }}
        };

        Rect scrollBounds = new Rect();
        View divider=findViewById(R.id.someview);
        myscollView.getHitRect(scrollBounds);
        if (!divider.getLocalVisibleRect(scrollBounds))  {
            // the divider view is NOT  within the visible scroll window thus we need to scroll a bit.
            myscollView.postDelayed(shifter, 500);
        }



    });

//по существу мы делаем runnable, который прокручивает к новому местоположению некоторого вида, которое вы ХОТИТЕ видеть на экране. вы выполняете этот runnable, только если его не в пределах scrollviews (его не на экране). Таким образом, он перемещает scrollview в ссылочный вид (в моем случае "someview", который был разделителем строк).

Ответ 4

По-моему, самый простой способ сделать это - это сочетание двух изменений:

android:windowSoftInputMode="adjustResize"

в вашем AndroidManifest.xml

+

getWindow().setBackgroundDrawable(your_image_drawable);

в вашей деятельности в методе @onCreate()

Это работает для меня.

Ответ 5

Лучшее решение - использовать DialogFragment

Показать диалог

DialogFragment.show(getSupportFragmentManager(), DialogFragment.TAG);

В полноэкранном режиме

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = new Dialog(getActivity(), R.style.MainDialog) { //set the style, the best code here or with me, we do not change
        @Override
        public void onBackPressed() {
            super.onBackPressed();
            getActivity().finish();
        }
    };
    return dialog;
}

Стиль

<style name="MainDialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowFrame">@null</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowIsFloating">false</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:background">@null</item>
        <item name="android:windowAnimationStyle">@null</item>
    </style>

Макетная деятельность

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Диалоговое окно диалога компоновки

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:background="@color/background_transparent_60"
        android:gravity="center_vertical">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/spacing_1_8dp"
            android:layout_marginLeft="@dimen/spacing_1_8dp"
            android:layout_marginRight="@dimen/spacing_1_8dp"
            android:layout_weight="1"
            android:hint="@string/comment_entry_hint"
            android:inputType="textMultiLine"
            android:maxLines="4"
            android:textColor="@color/white"
            android:textColorHint="@color/secondary_text_hint"
            android:textSize="@dimen/text_2_12sp" />

        <ImageView
            android:layout_width="@dimen/livestream_comment_height"
            android:layout_height="@dimen/livestream_comment_height"
            android:layout_margin="@dimen/spacing_1_8dp"
            android:src="@drawable/ic_send" />

    </LinearLayout>

</RelativeLayout>

Ответ 6

    final View activityRootView = findViewById(R.id.mainScroll);

    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
            new OnGlobalLayoutListener() {


                @Override
                public void onGlobalLayout() {
                    int heightView = activityRootView.getHeight();
                    int widthView = activityRootView.getWidth();
                    if (1.0 * widthView / heightView > 1) {

                        Log.d("keyboarddddd      visible", "no");
                        relativeLayoutForImage.setVisibility(View.GONE);
                        relativeLayoutStatic.setVisibility(View.GONE);
                        //Make changes for Keyboard not visible
                        //relativeLayoutForImage.setVisibility(View.VISIBLE);
                        //relativeLayoutStatic.setVisibility(View.VISIBLE);

                    } else {

                        Log.d("keyboarddddd      visible ", "yes");

                        relativeLayoutForImage.setVisibility(View.VISIBLE);
                        relativeLayoutStatic.setVisibility(View.VISIBLE);
                        //Make changes for keyboard visible

                    //  relativeLayoutForImage.setVisibility(View.GONE);
                        //relativeLayoutStatic.setVisibility(View.GONE);
                    }
                }
            });