Android How to adjust layout in Full Screen Mode when softkeyboard is visible

前端 未结 25 1778
后悔当初
后悔当初 2020-11-22 03:56

I have researched a lot to adjust the layout when softkeyboard is active and I have successfully implemented it but the problem comes when I use android:theme=\"@andro

相关标签:
25条回答
  • 2020-11-22 04:40

    I implemented Joseph Johnson solution and it worked well, I noticed after using this solution sometimes the drawer on the application will not close properly. I added a functionality to remove the listener removeOnGlobalLayoutListener when the user closes the fragment where are edittexts located.

        //when the application uses full screen theme and the keyboard is shown the content not scrollable! 
    //with this util it will be scrollable once again
    //http://stackoverflow.com/questions/7417123/android-how-to-adjust-layout-in-full-screen-mode-when-softkeyboard-is-visible
    public class AndroidBug5497Workaround {
    
    
        private static AndroidBug5497Workaround mInstance = null;
        private View mChildOfContent;
        private int usableHeightPrevious;
        private FrameLayout.LayoutParams frameLayoutParams;
        private ViewTreeObserver.OnGlobalLayoutListener _globalListener;
    
        // For more information, see https://code.google.com/p/android/issues/detail?id=5497
        // To use this class, simply invoke assistActivity() on an Activity that already has its content view set.
    
        public static AndroidBug5497Workaround getInstance (Activity activity) {
            if(mInstance==null)
            {
                synchronized (AndroidBug5497Workaround.class)
                {
                    mInstance = new AndroidBug5497Workaround(activity);
                }
            }
            return mInstance;
        }
    
        private AndroidBug5497Workaround(Activity activity) {
            FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
            mChildOfContent = content.getChildAt(0);
            frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
    
            _globalListener = new ViewTreeObserver.OnGlobalLayoutListener()
            {
    
                @Override
                public void onGlobalLayout()
                {
                     possiblyResizeChildOfContent();
                }
            };
        }
    
        public void setListener()
        {
             mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(_globalListener);
        }
    
        public void removeListener()
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                mChildOfContent.getViewTreeObserver().removeOnGlobalLayoutListener(_globalListener);
            } else {
                mChildOfContent.getViewTreeObserver().removeGlobalOnLayoutListener(_globalListener);
            }
        }
    
        private void possiblyResizeChildOfContent() {
            int usableHeightNow = computeUsableHeight();
            if (usableHeightNow != usableHeightPrevious) {
                int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
                int heightDifference = usableHeightSansKeyboard - usableHeightNow;
                if (heightDifference > (usableHeightSansKeyboard/4)) {
                    // keyboard probably just became visible
                    frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
                } else {
                    // keyboard probably just became hidden
                    frameLayoutParams.height = usableHeightSansKeyboard;
                }
                mChildOfContent.requestLayout();
                usableHeightPrevious = usableHeightNow;
            }
        }
    
        private int computeUsableHeight() {
            Rect r = new Rect();
            mChildOfContent.getWindowVisibleDisplayFrame(r);
            return (r.bottom - r.top);
        } 
    }
    

    uses the class where is my edittexts located

    @Override
    public void onStart()
    {
        super.onStart();
        AndroidBug5497Workaround.getInstance(getActivity()).setListener();
    }
    
    @Override
    public void onStop()
    {
        super.onStop();
        AndroidBug5497Workaround.getInstance(getActivity()).removeListener();
    }
    
    0 讨论(0)
  • 2020-11-22 04:41

    Please note that android:windowSoftInputMode="adjustResize" does not work when WindowManager.LayoutParams.FLAG_FULLSCREENis set for an activity. You've got two options.

    1. Either disable fullscreen mode for your activity. Activity is not re-sized in fullscreen mode. You can do this either in xml (by changing the theme of the activity) or in Java code. Add the following lines in your onCreate() method.

      getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);   
      getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);`
      

    OR

    1. Use an alternative way to achieve fullscreen mode. Add the following code in your onCreate() method.

      getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
      getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
      getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
      View decorView = getWindow().getDecorView();
      // Hide the status bar.
      int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
      decorView.setSystemUiVisibility(uiOptions);`
      

    Please note that method-2 only works in Android 4.1 and above.

    0 讨论(0)
  • 2020-11-22 04:43

    I just found a simple and reliable solution if you are using the system UI approach (https://developer.android.com/training/system-ui/immersive.html).

    It works in the case when you are using View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN, e.g. if you are using CoordinatorLayout.

    It won't work for WindowManager.LayoutParams.FLAG_FULLSCREEN (The one you can also set in theme with android:windowFullscreen), but you can achieve similar effect with SYSTEM_UI_FLAG_LAYOUT_STABLE (which "has the same visual effect" according to the docs) and this solution should work again.

    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION /* If you want to hide navigation */
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
    

    I've tested it on my device running Marshmallow.

    The key is that soft keyboards are also one of the system windows (such as status bar and navigation bar), so the WindowInsets dispatched by system contains accurate and reliable information about it.

    For the use case such as in DrawerLayout where we are trying to draw behind the status bar, We can create a layout that ignores only the top inset, and applies the bottom inset which accounts for the soft keyboard.

    Here is my custom FrameLayout:

    /**
     * Implements an effect similar to {@code android:fitsSystemWindows="true"} on Lollipop or higher,
     * except ignoring the top system window inset. {@code android:fitsSystemWindows="true"} does not
     * and should not be set on this layout.
     */
    public class FitsSystemWindowsExceptTopFrameLayout extends FrameLayout {
    
        public FitsSystemWindowsExceptTopFrameLayout(Context context) {
            super(context);
        }
    
        public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs,
                                                     int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs,
                                                     int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }
    
        @Override
        public WindowInsets onApplyWindowInsets(WindowInsets insets) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                setPadding(insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(),
                        insets.getSystemWindowInsetBottom());
                return insets.replaceSystemWindowInsets(0, insets.getSystemWindowInsetTop(), 0, 0);
            } else {
                return super.onApplyWindowInsets(insets);
            }
        }
    }
    

    And to use it:

    <com.example.yourapplication.FitsSystemWindowsExceptTopFrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <!-- Your original layout here -->
    </com.example.yourapplication.FitsSystemWindowsExceptTopFrameLayout>
    

    This should theoretically work for any device without insane modification, much better than any hack that tries to take a random 1/3 or 1/4 of screen size as reference.

    (It requires API 16+, but I'm using fullscreen only on Lollipop+ for drawing behind the status bar so it's the best solution in this case.)

    0 讨论(0)
  • 2020-11-22 04:43

    I was only using full screen mode to hide the status bar. However, I want the app to resize when keyboard is shown. All of the other solutions (likely due to age of post) were complicated or not possible for my use (want to avoid change Java code for sack of PhoneGap Build).

    Instead of using Full screen, I modified my configure for Android to be non-fullscreen:

                <preference name="fullscreen" value="false" />
    

    And added the cordova-plugin-statusbar, via command line:

    cordova plugin add cordova-plugin-statusbar
    

    When app has loaded, I simple call a method on the plugin to hide itself, like:

        if (window.cordova && window.cordova.platformId == 'android' && window.StatusBar)
            window.StatusBar.hide();
    

    This works like a charm. Only real downside is that the status bar is breifly visible while the app loads. For my needs, that wasn't an issue.

    0 讨论(0)
  • 2020-11-22 04:44

    only use android:windowSoftInputMode="adjustResize|stateHidden as you use AdjustPan then it disable the resizing property

    0 讨论(0)
  • 2020-11-22 04:45

    I'm currently using this approach and it works like a charm. The trick is we get keyboard height from different methods on 21 above and below and then use it as the bottom padding of our root view in our activity. I assumed your layout does not need a top padding (goes below status bar) but in case you do, inform me to update my answer.

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            RelativeLayout mainLayout = findViewById(R.id.main_layout);
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                ViewCompat.setOnApplyWindowInsetsListener(mainLayout , new OnApplyWindowInsetsListener() {
                    @Override
                    public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                        v.setPadding(0, 0, 0, insets.getSystemWindowInsetBottom());
                        return insets;
                    }
                });
            } else {
                View decorView = getWindow().getDecorView();
                final View contentView = mainLayout;
                decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        Rect r = new Rect();
                        //r will be populated with the coordinates of your view that area still visible.
                        decorView.getWindowVisibleDisplayFrame(r);
    
                        //get screen height and calculate the difference with the useable area from the r
                        int height = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
                        int diff = height - r.bottom;
    
                        //if it could be a keyboard add the padding to the view
                        if (diff != 0) {
                            // if the use-able screen height differs from the total screen height we assume that it shows a keyboard now
                            //check if the padding is 0 (if yes set the padding for the keyboard)
                            if (contentView.getPaddingBottom() != diff) {
                                //set the padding of the contentView for the keyboard
                                contentView.setPadding(0, 0, 0, diff);
                            }
                        } else {
                            //check if the padding is != 0 (if yes reset the padding)
                            if (contentView.getPaddingBottom() != 0) {
                                //reset the padding of the contentView
                                contentView.setPadding(0, 0, 0, 0);
                            }
                        }
                    }
                });
            }
        }
    ...
    }
    

    Don't forget to address your root view with an id:

    activity_main.xml

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/main_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    

    Hope it helps someone.

    0 讨论(0)
提交回复
热议问题