2016-03-10 19 views
12

Desidero visualizzare automaticamente un listview con la stessa altezza della tastiera del dispositivo quando l'utente accede a quella particolare attività. Per questo, sto chiamando tre metodi che sono, showKeyboard(), getKeyboardHeight() e quindi hideKeyboard() e quindi dando l'altezza a tale listview e mostrando tale listview. Ma il problema è una volta che chiamo showKeyboard(), calcoli l'altezza e poi hideKeyboard(), la tastiera non si nasconde e rimane visibile. Inoltre sto ottenendo altezza come 0. Non riesco a visualizzare quel listView. C'è qualche altro processo per ottenere l'altezza della tastiera o qualsiasi correzione nel codice sottostante? Vedere il codice qui sotto:Come ottenere l'altezza della tastiera quando l'attività viene creata in Android

showKeyboard metodo() -

metodo getKeyboardHeight() - Metodo

public int getKeyboardHeight() { 
      final View rootview = this.getWindow().getDecorView(); 
      linearChatLayout.getViewTreeObserver().addOnGlobalLayoutListener(
       new ViewTreeObserver.OnGlobalLayoutListener() { 
        public void onGlobalLayout() { 
         Rect r = new Rect(); 
         rootview.getWindowVisibleDisplayFrame(r); 
         int screenHeight = rootview.getRootView().getHeight(); 
         int newHeight = screenHeight - (r.bottom - r.top); 
         if (newHeight > heightOfKeyboard) { 
          heightOfKeyboard = screenHeight 
            - (r.bottom - r.top); 
          // heightOfKeyboard = heightDiff; 
         } 

         Log.d("Keyboard Size", "Size: " + heightOfKeyboard); 
        } 
       }); 
     return heightOfKeyboard; 
    } 

hideKeyboard() -

private void hidekeyBoard() { 
      InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
      imm.hideSoftInputFromWindow(editChatBox.getWindowToken(), 0); 
} 
Metodo

All'interno onCreate() -

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

    ArrayAdapter<String> chatQueAdapter = new ArrayAdapter<>(this, 
      R.layout.chat_que_row, R.id.textChatQue, queArrays); 
    myListView.setAdapter(chatQueAdapter); 

     showKeyboard(); 
     heightOfKeyboard = getKeyboardHeight(); 
     hidekeyBoard(); 
     myListView.getLayoutParams().height = heightOfKeyboard; 
     myListView.setVisibility(View.VISIBLE); 
    } 
+0

Non è possibile ottenere altezza della tastiera prima della sua prima apertura. Per la prima volta è possibile utilizzare il valore predefinito (ad esempio 230 dpi) e quindi regolare il valore. E imposta windowSoftInputMode per adjustResize. –

+0

@gabber ma sto aprendo la tastiera usando il metodo showKeyboard() e quindi calcolando l'altezza e nascondendola usando il metodo hideKeyboard(). Sto ottenendo altezza zero e la tastiera rimane aperta. – Ruchir

+0

per essere in grado di calcolare la dimensione in modo tale, è necessario impostare windowSoftInputMode per regolare Ridimensiona –

risposta

2

Ho aggiunto il layout globale alla vista principale e sono stato in grado di ridimensionare la visualizzazione elenco con le stesse dimensioni della tastiera.

La casella rosa è il ListView ridimensionato. Ho provato questa app di esempio su 2 dispositivi Samsung e funziona bene su entrambi.

enter image description here

layout File

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 

    <EditText 
     android:id="@+id/edt" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:focusable="true" 
     android:focusableInTouchMode="true" 
     android:inputType="text" 
     android:maxLines="1" /> 

    <ListView 
     android:id="@+id/list" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:background="@color/colorAccent" 
     android:visibility="gone" /> 
</LinearLayout> 

Classe di attività

import android.graphics.Rect; 
import android.os.Build; 
import android.os.Bundle; 
import android.support.v4.view.PagerAdapter; 
import android.support.v4.view.ViewPager; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.util.TypedValue; 
import android.view.View; 
import android.view.ViewGroup; 
import android.view.ViewTreeObserver; 
import android.widget.EditText; 
import android.widget.ListView; 
import android.widget.Toast; 

import com.fet.minebeta.R; 

public class ListActivity extends AppCompatActivity { 

    PagerAdapter adapterViewPager; 
    ViewPager viewPager; 
    private int heightDiff; 
    private ListView myListView; 
    private EditText editChatBox; 

    private boolean wasOpened; 
    private final int DefaultKeyboardDP = 100; 
    // Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff 
    private final int EstimatedKeyboardDP = DefaultKeyboardDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0); 

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

     myListView = (ListView) findViewById(R.id.list); 
     editChatBox = (EditText) findViewById(R.id.edt); 

     //Listen for keyboard height change 
     setKeyboardListener(); 

//  InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); 
//  editChatBox.requestFocus(); 
//  inputMethodManager.showSoftInput(editChatBox, 0); 
// 
//  if (getCurrentFocus() != null) { 
//   inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); 
//   inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); 
//  } 
// 
//  getWindow().setSoftInputMode(
//    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN 
//  ); 
    } 


    public final void setKeyboardListener() { 

     final View activityRootView = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0); 

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

      private final Rect r = new Rect(); 

      @Override 
      public void onGlobalLayout() { 
       // Convert the dp to pixels. 
       int estimatedKeyboardHeight = (int) TypedValue 
         .applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, activityRootView.getResources().getDisplayMetrics()); 

       // Conclude whether the keyboard is shown or not. 
       activityRootView.getWindowVisibleDisplayFrame(r); 
       heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top); 
       boolean isShown = heightDiff >= estimatedKeyboardHeight; 

       if (isShown == wasOpened) { 
        Log.d("Keyboard state", "Ignoring global layout change..."); 
        return; 
       } 

       wasOpened = isShown; 

       if (isShown) { 

        //Set listview height 
        ViewGroup.LayoutParams params = myListView.getLayoutParams(); 
        params.height = heightDiff; 
        myListView.setLayoutParams(params); 
        myListView.requestLayout(); 
        myListView.setVisibility(View.VISIBLE); 

        Toast.makeText(ListActivity.this, "KeyBoard Open with height " + heightDiff + 
          "\n List View Height " + myListView.getHeight(), Toast.LENGTH_SHORT).show(); 

       } 
      } 
     }); 
    } 
} 

Anche in questo caso è solo veloce demo è possibile migliorare le cose secondo le vostre necessità.

+0

Ho provato la soluzione. Sto ricevendo l'altezza della tastiera, ma solo quando clicco su edittext che consente di aprire la tastiera. Stavo cercando di aprire la tastiera manualmente e quindi assegnare quell'altezza a listView senza usare editText. Questo è y ho scritto il metodo showKeyboard(). E 'possibile senza editText click? – Ruchir

1

Per quanto ne so, non c'è soluzione perfetta che funziona per tutto il tempo. Ho visto molte persone usare ViewTreeObserver per ottenere l'altezza della tastiera, anche se questo non funzionerebbe a volte, è meglio di niente. Try it out.

Ho scritto un Input Method Editor alcuni anni fa. Come ricordo, non esiste una funzione chiamata "getCurrentHeight" esposta dalle classi IME. Quindi non andare in questo modo.

E si noti che al giorno d'oggi molti supporto IME per modificare l'altezza della tastiera in fase di esecuzione (quando viene visualizzato sullo schermo), forse si dovrebbe tenerne conto.

0

ho capito altezza utilizzando personalizzato poi passare calcolarlo

private int keyboardHeight; 

// passed here 230dp 
final float popUpheight = getResources().getDimension(
      R.dimen.keyboard_height); 
    changeKeyboardHeight((int) popUpheight); 

// call this where you want height of keyboard 
checkKeyboardHeight(); 

int previousHeightDiffrence = 0; 

private void checkKeyboardHeight() { 

    rootlayout.getViewTreeObserver().addOnGlobalLayoutListener(
      new ViewTreeObserver.OnGlobalLayoutListener() { 

       @Override 
       public void onGlobalLayout() { 

        Rect r = new Rect(); 
        rootlayout.getWindowVisibleDisplayFrame(r); 
        int screenHeight = rootlayout.getRootView() 
          .getHeight(); 
        int heightDifference = screenHeight - (r.bottom); 

        if (Math.abs(previousHeightDiffrence - heightDifference) > 50) { 
         popupWindow.dismiss(); 
         imageEmoji 
           .setImageResource(R.drawable.emoji_btn_normal); 
        } 

        previousHeightDiffrence = heightDifference; 
        if (heightDifference > 100) { 
         isKeyBoardVisible = true; 
         changeKeyboardHeight(heightDifference); 
        } else { 
         isKeyBoardVisible = false; 
        } 

       } 
      }); 
} 


/** 
* change height of emoticons keyboard according to height of actual 
* keyboard 
* 
* @param height minimum height by which we can make sure actual keyboard is 
*    open or not 
*/ 
private void changeKeyboardHeight(int height) { 

    if (height > 100) { 
     keyboardHeight = height; 
     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
       LayoutParams.MATCH_PARENT, keyboardHeight); 
     emoticonsCover.setLayoutParams(params); 
    } 

} 

per maggiori dettagli Checkout dal here, Spero che questo ti aiuti

0

Utilizza OnGlobalLayoutListener per ottenere l'altezza della tastiera o implementare sopra lo snippet di codice

chatRootLayout è il tuo XML di layout radice passare questo rootLayout come parametro di parentLayout in checkKeyboardHeight

private void checkKeyboardHeight(final View parentLayout) 
{ 
    chatRootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() 
    { 
     @Override 
     public void onGlobalLayout() 
     { 
       Rect r = new Rect(); 

       chatRootLayout.getWindowVisibleDisplayFrame(r); 

       int screenHeight = chatRootLayout.getRootView().getHeight(); 
       int keyboardHeight = screenHeight - (r.bottom); 

       if (previousHeightDiffrence - keyboardHeight > 50) 
       {       
        // Do some stuff here 
       } 

       previousHeightDiffrence = keyboardHeight; 
       if (keyboardHeight> 100) 
       { 
        isKeyBoardVisible = true; 
        changeKeyboardHeight(keyboardHeight); 
       } 
       else 
       { 
        isKeyBoardVisible = false; 
       } 
      } 
    }); 
} 

keyboardHeight() Metodo: -

private void changeKeyboardHeight(int height) 
{ 
    if (height > 100) 
    { 
      keyboardHeight = height; 
      LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, keyboardHeight); 
      yourLayout.setLayoutParams(params); 
    } 
}