tccpg288 tccpg288 - 21 days ago 5
Java Question

Implement Search Bar on Activity Load

I want to load an activity and have the search bar visible right away with a magnifying glass available to click/search based on the term entered. Here is what I want to see when I load the activity:

enter image description here

Code:

public class FlickRActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flick_r);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);

MenuItem searchItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}

@Override
public boolean onQueryTextChange(String newText) {
Toast.makeText(getApplicationContext(),newText,Toast.LENGTH_SHORT).show();
return false;
}
});

return true;
}

}


Menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/search"
android:title="@string/hint_search"
android:icon="@android:drawable/ic_menu_search"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>

Answer

Just call searchItem.expandActionView();

Comments