简体   繁体   中英

Android: show white background when search button pressed

When I press the search key on my device, I want it to show a white background. However, when I press the back button, I want the previous activity's background to be restored. ivBackground is a variable I added to my relativelayout which I turn VISIBLE to show the white background.

 public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_SEARCH) {
        ivBackground.setVisibility(View.VISIBLE);//WHITE IMAGEVIEW
        return false;
    } else if (keyCode == KeyEvent.KEYCODE_BACK) {
        ivBackground.setVisibility(View.GONE);
        return true;
    }
    return super.onKeyDown(keyCode, event);
 } 

While the above code works, the problem is that when I press the back button, the white screen still remains. It only goes away if I press the back button once again. Any solutions?

On the relevant activity, you can get a reference to a SearchManager object. On this, you can set an OnDismissListener , which is called the when search UI is dismissed eg

this.searchMgr = (SearchManager)this.getSystemService(Context.SEARCH_SERVICE);
this.searchMgr.setOnDismissListener(new OnDismissListener() {
    public void onDismiss() {
        ivBackground.setVisibility(View.GONE);
    }
});

To make the white background visible, you can override onSearchRequested inside your activity class, which is called when a user signals the desire to start a search

@Override
public boolean onSearchRequested() {
    ivBackground.setVisibility(View.VISIBLE);
    return super.onSearchRequested();
}

Hope this helps!

How about setting a SearchView.OnCloseListener or a SearchManager.OnDismissListener that also hides your view? This seems like the right solution anyway since the two events are logically connected. If you later dismiss the search view programmatically for example, you don't have to worry about separately dismissing the background view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM