首先从搜索 (layout_search.xml) 创建您的 xml 布局:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<AutoCompleteTextView
android:id="@+id/edit_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search" >
<requestFocus />
</AutoCompleteTextView>
<ImageView
android:id="@+id/img_clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:src="@drawable/ic_menu_clear" />
</FrameLayout>
在您的菜单 xml 中:
<item
android:id="@+id/menu_search"
android:icon="@drawable/ic_menu_search"
android:showAsAction="always|collapseActionView"
android:title="Search">
</item>
创建菜单:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menuyour_menu, menu);
menu.getItem(0).setActionView(R.layout.layout_search);
AutoCompleteTextView search = (AutoCompleteTextView) mI.getActionView().findViewById(R.id.edit_search);
ImageView imgClear = (ImageView) menu.getItem(0).getActionView().findViewById(R.id.img_clear).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
search.setText("");
}
});
return super.onCreateOptionsMenu(menu);
}