[英]Android ViewPager show soft keyboard in the wrong place
我使用帶有 3 個片段的 ViewPager。 第一個只有文本。 第二個,輸入框。 第三,只有文字。
當 ViewPager 初始化時,顯示軟鍵盤,因為焦點設置在輸入字段。 如果我更改片段的順序,則不會顯示軟鍵盤。
如何使用 ViewPager 控制焦點和軟鍵盤?
問候
到目前為止,我發現的最佳解決方案是在您的活動清單中使用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
技巧,因為當您滑回無輸入片段時鍵盤不會隱藏。 雖然我想你可以將它與上面的代碼結合起來。
我確信有更好的方法來做到這一點,但我遇到了同樣的問題,我通過將父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>
感謝大家,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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.