Android: Redimensionnez uniquement les parties de la vue avec le clavier logiciel à l’écran

J’ai une vue avec un champ Edittext sur un ImageView. Lorsque le clavier apparaît, je souhaite redimensionner la fenêtre pour que EditText ne soit plus masqué par le clavier. Dans le fichier AndroidManifest, j’ai déclaré android:windowSoftInputMode="adjustResize" et l’écran est redimensionné, mais le problème est que je veux que ImageView ne soit pas redimensionné. Comment puis-je rendre l’ImageView non affecté?

Est-ce que je pourrais gonfler une mise en page supplémentaire avec le seul ImageView ou le redimensionnement l’affecterait-il toujours? entrer la description de l'image ici

La solution complète implique quelques points clés

  • Utilisez RelativeLayout , de sorte que les Views puissent être configurées pour se chevaucher
  • Alignez le EditText avec le bas de Windows utilisant android:layout_alignParentBottom="true"
  • Utilisez android:windowSoftInputMode="adjustResize" dans votre manifeste, de sorte que le bas de la Window change lorsque le clavier apparaît (comme vous l’avez mentionné)
  • Placez le ImageView dans un ScrollView pour que l’ ImageView soit plus grand que la Window et désactivez le défilement sur ScrollView en utilisant ScrollView#setEnabled(false)

Voici le fichier de mise en page

       

Voici mon activité

 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); } } 

Mon AndroidManifest

            

Captures d’écran de ma solution

capture d'écran 1capture d'écran 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 } } }); 

Pour moi, je ne voulais pas supposer que les hauteurs de claviers sont une certaine mesure. Quel que soit le sharepoint vue de votre inquiétude, créez un onTouchListener, puis procédez comme suit:

  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); } }); 

// Essentiellement, nous rendons exécutable un nouvel emplacement de vue que vous souhaitez voir apparaître à l’écran. vous exécutez cette exécution uniquement si ce n’est pas dans les limites de scrollviews (ce n’est pas à l’écran). De cette façon, il déplace la vue de défilement vers la vue référencée (dans mon cas, «vue d’ensemble», qui était un diviseur de ligne).

À mon avis, la manière la plus simple de faire cela est cette combinaison des deux changements :

 android:windowSoftInputMode="adjustResize" 

dans votre AndroidManifest.xml

+

 getWindow().setBackgroundDrawable(your_image_drawable); 

dans votre activité dans la méthode @onCreate ()

Ça marche pour moi.

La meilleure solution consiste à utiliser un DialogFragment

Afficher la boîte de dialog

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

Plein écran

 @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

  

Activité de mise en page

     

Fragment de dialog de mise en page

        

L’ajout de ScrollView rendait mon image défilable que je voulais éviter. J’ai donc utilisé cette calculasortingce samples-keyboardheight et la position recalculée par onKeyboardHeightChanged du Edittext inférieur l’ Edittext placée au-dessus du clavier et utilisé cet indicateur dans Manifest.

 android:windowSoftInputMode="adjustNothing|stateHidden" 

Voici KeyboardHeightProvider :

 import android.app.Activity; import android.content.res.Configuration; import android.graphics.Point; import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.view.WindowManager.LayoutParams; import android.widget.PopupWindow; /** * The keyboard height provider, this class uses a PopupWindow * to calculate the window height when the floating keyboard is opened and closed. */ public class KeyboardHeightProvider extends PopupWindow { /** The tag for logging purposes */ private final static Ssortingng TAG = "sample_KeyboardHeightProvider"; /** The keyboard height observer */ private KeyboardHeightObserver observer; /** The cached landscape height of the keyboard */ private int keyboardLandscapeHeight; /** The cached portrait height of the keyboard */ private int keyboardPortraitHeight; /** The view that is used to calculate the keyboard height */ private View popupView; /** The parent view */ private View parentView; /** The root activity that uses this KeyboardHeightProvider */ private Activity activity; /** * Construct a new KeyboardHeightProvider * * @param activity The parent activity */ public KeyboardHeightProvider(Activity activity) { super(activity); this.activity = activity; LayoutInflater inflator = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); this.popupView = inflator.inflate(R.layout.popupwindow, null, false); setContentView(popupView); setSoftInputMode(LayoutParams.SOFT_INPUT_ADJUST_RESIZE | LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); parentView = activity.findViewById(android.R.id.content); setWidth(0); setHeight(LayoutParams.MATCH_PARENT); popupView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (popupView != null) { handleOnGlobalLayout(); } } }); } /** * Start the KeyboardHeightProvider, this must be called after the onResume of the Activity. * PopupWindows are not allowed to be registered before the onResume has finished * of the Activity. */ public void start() { if (!isShowing() && parentView.getWindowToken() != null) { setBackgroundDrawable(new ColorDrawable(0)); showAtLocation(parentView, Gravity.NO_GRAVITY, 0, 0); } } /** * Close the keyboard height provider, * this provider will not be used anymore. */ public void close() { this.observer = null; dismiss(); } /** * Set the keyboard height observer to this provider. The * observer will be notified when the keyboard height has changed. * For example when the keyboard is opened or closed. * * @param observer The observer to be added to this provider. */ public void setKeyboardHeightObserver(KeyboardHeightObserver observer) { this.observer = observer; } /** * Get the screen orientation * * @return the screen orientation */ private int getScreenOrientation() { return activity.getResources().getConfiguration().orientation; } /** * Popup window itself is as big as the window of the Activity. * The keyboard can then be calculated by extracting the popup view bottom * from the activity window height. */ private void handleOnGlobalLayout() { Point screenSize = new Point(); activity.getWindowManager().getDefaultDisplay().getSize(screenSize); Rect rect = new Rect(); popupView.getWindowVisibleDisplayFrame(rect); // REMIND, you may like to change this using the fullscreen size of the phone // and also using the status bar and navigation bar heights of the phone to calculate // the keyboard height. But this worked fine on a Nexus. int orientation = getScreenOrientation(); int keyboardHeight = screenSize.y - rect.bottom; if (keyboardHeight == 0) { notifyKeyboardHeightChanged(0, orientation); } else if (orientation == Configuration.ORIENTATION_PORTRAIT) { this.keyboardPortraitHeight = keyboardHeight; notifyKeyboardHeightChanged(keyboardPortraitHeight, orientation); } else { this.keyboardLandscapeHeight = keyboardHeight; notifyKeyboardHeightChanged(keyboardLandscapeHeight, orientation); } } /** * */ private void notifyKeyboardHeightChanged(int height, int orientation) { if (observer != null) { observer.onKeyboardHeightChanged(height, orientation); } } public interface KeyboardHeightObserver { void onKeyboardHeightChanged(int height, int orientation); } } 

popupwindow.xml:

   

Voici MainActivity.java :

 import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; public class MainActivity extends AppCompatActivity implements KeyboardHeightProvider.KeyboardHeightObserver { private KeyboardHeightProvider keyboardHeightProvider; private ViewGroup relativeView; private float initialY; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); keyboardHeightProvider = new KeyboardHeightProvider(this); relativeView = findViewById(R.id.bottomEditor); relativeView.post(() -> initialY = relativeView.getY()); View view = findViewById(R.id.activitylayout); view.post(() -> keyboardHeightProvider.start()); } @Override public void onKeyboardHeightChanged(int height, int orientation) { if(height == 0){ relativeView.setY(initialY); relativeView.requestLayout(); }else { float newPosition = initialY - height; relativeView.setY(newPosition); relativeView.requestLayout(); } } @Override public void onPause() { super.onPause(); keyboardHeightProvider.setKeyboardHeightObserver(null); } @Override public void onResume() { super.onResume(); keyboardHeightProvider.setKeyboardHeightObserver(this); } @Override public void onDestroy() { super.onDestroy(); keyboardHeightProvider.close(); } } 

activity_main.xml :

         

PS: le code de calcul de la hauteur du clavier est copié à partir de siebeprojects

Voici un exemple d’application de mise en œuvre.

La solution qui a fonctionné pour moi était dans AndroidManifest.xml dans cette balise d’activité juste mettre

 android:windowSoftInputMode="stateHidden|adjustResize|adjustNothing" 

Tous ensemble .. Espérons que cela fonctionnera pour vous.

  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); } } });