Thanh Nam Pham Thanh Nam Pham - 12 days ago 8
Android Question

How to intent to other activity when icon search clicked

I have the problem, I use icon search on Toolbar, I want to click this icon search, it will move to new activity and expand editview search in here, but my code can not achive

My class (First Activity):

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu_icon_toolbar, menu);
// Retrieve the SearchView and plug it into SearchManager
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if(item.getItemId()==R.id.action_search){
Intent i = new Intent(this,SearchCarActivity.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}


my layout_activity:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<!-- NavigationDrawer Menu -->
<item android:id="@+id/action_search"
android:title="Search"
app:showAsAction="always"
android:icon="@drawable/ic_action_name_search"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
</menu>


My Search activity (Second activity):

public class SearchCarActivity extends AppCompatActivity {

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_car_menu, menu);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setIconified(false);
return super.onCreateOptionsMenu(menu);
}
}


My search_car_menu.xml:

<?xml version="1.0" encoding="utf-8"?>




<item
android:id="@+id/search"
android:icon="@android:drawable/ic_menu_search"
android:title="Search"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"/>




It does't move to second activity, it seem still achive in first activity

How to I can achive move to second activity when clicked icon search on Toolbar?

Thanks

Answer

I created a test project an added your code from what you said you want to click on the search icon on the first activity and then open second activity and do your search there

removing this line from your layout_activity did the trick :

app:actionViewClass="android.support.v7.widget.SearchView"

when you added that line your item would behave as a SearchView and not even respond to

public boolean onOptionsItemSelected(MenuItem item)
Comments