我在如何在活动中编写代码以实际实现将onClick事件从该活动转到我的主页方面遇到问题。我应该在mainactivity中添加什么以便实现onclick转到另一个活动?
searchmenu.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/action_search"
android:title="Search"
android:icon="@android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView" />
<item
android:id="@+id/action_home"
android:title="Home"
android:icon="@drawable/ic_home2"
app:showAsAction="always|collapseActionView" />
</menu>
活动:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.searchmenu, menu);
final MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) myActionMenuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String text) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_home:
startActivity(new Intent(AuctionList.this,SignIn.class));
return true;
default:
break;
}
return false;
}
答案 0 :(得分:1)
您可能想尝试一下:
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.searchmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_home:
// Do menu item stuff here
return true;
default:
break;
}
return false;
}
答案 1 :(得分:0)
尝试此代码。 该代码用于活动中。.
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.searchmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_home:
// Do menu item stuff here
return true;
default:
break;
}
return false;
}
下面在片段中使用的代码。
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.search_menu, menu) // define menu file name
}
//单击事件句柄
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item!!.itemId) {
R.id.mnSearchProduct -> {
// call your fragment.
}
}
return super.onOptionsItemSelected(item)
}