在res目录下新建menu文件下,再新建main.xml输入以下代码
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
app:showAsAction="ifRoom"
android:title="@string/search_string"
android:id="@+id/action_search"
android:orderInCategory="1"></item>
</menu>
MainActivity需要重写 onCreateOptionsMenu(Menu menu) 和 onOptionsItemSelected(MenuItem item) 方法
public class MainActivity extends AppCompatActivity {
private EditText mSearchBoxEditText;
private TextView mUrlDisplayTextView;
private TextView mSearchResultsTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSearchBoxEditText = (EditText) findViewById(R.id.et_search_box);
mUrlDisplayTextView = (TextView) findViewById(R.id.tv_url_display);
mSearchResultsTextView = (TextView) findViewById(R.id.tv_github_search_results_json);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemID = item.getItemId();
if(itemID==R.id.action_search){
Context context = MainActivity.this;
Toast.makeText(context,"search clicked",Toast.LENGTH_LONG).show();
return true;
}else{
return super.onOptionsItemSelected(item);
}
}
}
网友评论