Custom SearchView whole clickable in android

[亡魂溺海] 提交于 2019-12-04 22:41:00

By default the SearchView is 'iconified', which is displayed as a magnifying glass icon and only if the user clicks on the icon, then the edit field expands.

To enable the user to click anywhere on the SearchView and expand the input field. We just need to add a click listener and call setIconified(false) when the user clicks.

searchView = (SearchView)findViewById(R.id.searchView);
searchView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            searchView.setIconified(false);
        }
    });

Another simple way to do it by setting onActionViewExpanded().

searchView = (SearchView)findViewById(R.id.searchView);
searchView.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        searchView.onActionViewExpanded();
    }
});

To allow writing when clicking in the whole component, I'd recommend you declaring iconifiedByDefault="false" on the xml.

<SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:iconifiedByDefault="false"/>

By default the SearchView is 'iconified'. So you should use this code in java:

SearchView searchView = (SearchView) findViewById(R.id.searchView);
searchView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        searchView.setIconified(false);
    }
});

or use this in xml:

<SearchView
        android:id="@+id/searchView"
        android:iconifiedByDefault="false" />

this 2 ways is correct, but different in icons display.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!