2012-02-03 79 views
5

我使用了一個帶有3片段的ViewPager。 第一個只有文本。 第二個是輸入字段。 第三隻,文字。Android ViewPager在錯誤的地方顯示軟鍵盤

當ViewPager初始化時,顯示軟鍵盤,因爲焦點被設置爲輸入字段。 如果我更改片段的順序,則不會顯示軟鍵盤。

如何使用ViewPager控制焦點和軟鍵盤?

問候

+0

也許你可以強制隱藏軟鍵盤。更多細節在這裏: http://stackoverflow.com/questions/1109022/how-to-close-hide-the-android-soft-keyboard – 2012-02-03 12:19:20

回答

1

我敢肯定有更好的方式來做到這一點,但我有同樣的問題,我由父View設置爲可聚焦了周圍。這樣一來,無論是從彈出當你在頁面之間輕掃不會接收焦點引起軟鍵盤...

<!-- Dummy item to prevent your View from receiving focus --> 
<LinearLayout 
    ... 
    android:focusable="true" 
    android:focusableInTouchMode="true" /> 

    <!-- The view(s) that are causing the keyboard to pop up each time you swipe --> 
    <EditText ... /> 

</LinearLayout> 
+0

可悲的是,它不會隱藏鍵盤,當你回到沒有片段edittexts。 – Timmmm 2012-09-14 10:15:36

5

到目前爲止,我已經找到了最好的解決方案是在您的活動的清單以使用android:windowSoftInputMode="stateHidden",和然後將其添加到您的活動中。

@Override 
public void onPageScrollStateChanged(int state) 
{ 
    if (state == ViewPager.SCROLL_STATE_IDLE) 
    { 
     if (mViewPager.getCurrentItem() == 0) 
     { 
      // Hide the keyboard. 
      ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)) 
       .hideSoftInputFromWindow(mViewPager.getWindowToken(), 0); 
     } 
    } 
} 

我沒有使用onPageSelected()因爲揮動動畫隱藏鍵盤動畫螺絲。而且我沒有使用android:focusable技巧,因爲當您滑回無輸入片段時,鍵盤未隱藏。雖然我想你可以將它與上面的代碼結合起來。

0

感謝大家,Timmmm非常有幫助。 我終於把所有東西都包了起來,並得到了一個完整的軟鍵盤隱藏解決方案,用於標籤刷卡。 我有4個標籤,每個都有editTexts,而且我需要在滑動時隱藏鍵盤。 我說這片段佈局:已添加到活動代碼

<!--Fixes keboard pop-up--> 
<LinearLayout 
    android:layout_width="0dp" 
    android:layout_height="0dp" 
    android:background="@android:color/transparent" 
    android:focusable="true" 
    android:focusableInTouchMode="true"> 
</LinearLayout> 

(注意用Timmmm的回答有點區別:我還沒有得到

mViewPager.getCurrentItem() == 0 

在這裏,因爲我需要隱藏鍵盤爲每一個觀點:

// When swiping between different sections, select the corresponding 
    // tab. We can also use ActionBar.Tab#select() to do this if we have 
    // a reference to the Tab. 
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { 
     @Override 
     public void onPageSelected(int position) { 
      if (actionBar != null) { 
       actionBar.setSelectedNavigationItem(position); 
      } 
     } 
     @Override 
     public void onPageScrollStateChanged(int state) 
     { 
      if (state == ViewPager.SCROLL_STATE_IDLE) 
      { 
       // Hide the keyboard. 
       ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)) 
         .hideSoftInputFromWindow(mViewPager.getWindowToken(), 0); 

      } 
     } 
    }); 

這裏是在AndroidManifest.xml中活動:

<activity 
     android:name=".TestActivity" 
     android:label="@string/title_activity_test" 
     android:parentActivityName=".MainActivity" 
     android:windowSoftInputMode="stateHidden"> 
     <meta-data 
      android:name="android.support.PARENT_ACTIVITY" 
      android:value="com.atrinax.test.MainActivity" /> 
</activity>