如何在actionbar
搜索小部件中触发操作?
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_search:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:3)
进行布局搜索并向其添加EditText。
<EditText
android:id="@+id/txt_search"
android:layout_width="400dp"
android:layout_height="wrap_content"
android:drawableRight="@drawable/ic_action_search"
/>
并且该项目到菜单 activity_main.xml使xml像这样
<item android:id="@+id/ser"
android:icon="@drawable/ic_action_search"
android:title="Search"
android:showAsAction="always"
android:actionLayout="@layout/search">
</item>
代码
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
View v = (View) menu.findItem(R.id.ser).getActionView();
final EditText txtSearch = ( EditText ) v.findViewById(R.id.txt_search);
txtSearch.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
// TODO Auto-generated method stub
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txtSearch.getWindowToken(), 0);
String mname=v.getText().toString().replaceAll("\\s","");
StringBuilder sn=new StringBuilder();
sn.append("http://www....");
Intent intent=new Intent(getApplicationContext(),Moviesearch.class);
final String finurl=sn.toString();
intent.putExtra("urlid",finurl);
startActivity(intent);
return false;
}
});
return true;