2016-07-16 73 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>