2016-07-16 74 views
13

我想從SearchView中刪除onResume()中的焦點和文本。我試過searchView.clearFocus()但它不工作。如何從SearchView中刪除焦點?

這是我的XML代碼:

<SearchView 
    android:id="@+id/searchView" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignBottom="@+id/toolbar" 
    android:layout_alignTop="@+id/toolbar" 
    android:layout_centerVertical="true" 
    android:layout_marginBottom="4dp" 
    android:layout_marginTop="4dp" 
    android:iconifiedByDefault="false" 
    android:paddingLeft="16dp" 
    android:paddingRight="16dp" /> 
+0

它是如何不工作?造成某種錯誤或者什麼都沒有發生?請更具描述性...... – Vucko

+0

顯示您的代碼好友:) – tinku

+0

@Vucko實際上它不顯示任何錯誤,並且光標不會刪除。 –

回答

20

你可以設置你的根佈局可聚焦在onResume()android:focusableInTouchMode屬性,並要求關注那些View

例如:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/root_layout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:focusableInTouchMode="true"> 

    <SearchView 
     android:id="@+id/search_view" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:iconifiedByDefault="false"/> 

</LinearLayout> 

,然後在Activity

private View rootView; 
private SearchView searchView; 

// ... 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    // ... 

    rootView = findViewById(R.id.root_layout); 
    searchView = (SearchView) findViewById(R.id.search_view); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 

    searchView.setQuery("", false); 
    rootView.requestFocus(); 
} 
2

使用此行代碼在你的onResume方法

if (searchView != null) { 
    searchView.setQuery("", false); 
    searchView.clearFocus(); 
    searchView.onActionViewCollapsed(); 
} 
+0

這是禁用我的focusListner,我不想要的,我只是想每當點擊它應該回來。當碎片再次加載時,它應該刪除。 –

+0

你的問題不像你現在解釋的那樣。 (我想從onResume()中的SearchView中刪除焦點和文本我試過searchView.clearFocus();但它不工作。) – Masum

+0

對不起:/但謝謝!求助。 –

0

最簡單的(我想,只有100%的工作)的解決方案是,以創建一個無形的LinearLayout。這LinearLayout將抓住從EditText的重點。

0

寫代碼onResume()

searchView.setText("");  
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);  
6

當活動進入父佈局,並在fragment太也在做同樣的事情在framelayout。只需添加此屬性:

android:focusableInTouchMode="true" 
0

我剛剛請求關注某個其他視圖組,並將焦點從searchview中移除。

0

我只是使用android:focusable="false"

<SearchView 
     android:layout_width="match_parent" 
     android:id="@+id/search" 
     android:paddingLeft="8dp" 
     android:paddingRight="8dp" 
     android:focusable="false" 
     android:iconifiedByDefault="false" 
     android:layout_height="wrap_content"> 
</SearchView>