我正在尝试使用 ActionBar Sherlock 实现 Action Bar。我有三个操作按钮,其中一个是搜索按钮。单击搜索按钮时,应显示我已经实现的搜索输入字段。但我希望它占据操作栏的整个宽度。知道我如何能达到同样的效果。
问问题
16367 次
1 回答
23
首先制作一个editTextLayout
布局搜索.xml
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/search_edit_text"
android:cursorVisible="true"
android:hint="@string/search_friend_hint"
android:imeOptions="actionDone"
android:inputType="text"
android:textColor="@android:color/black"
android:textCursorDrawable="@android:color/black" />
在您的菜单 xml 添加android:actionLayout
和android:showAsAction="always|collapseActionView"
搜索选项。对于其他选项android:showAsAction="ifRoom"
菜单.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:icon="@drawable/ic_action_sort"
android:orderInCategory="1"
android:showAsAction="ifRoom"
android:title="@string/menu_sort"/>
<item
android:id="@+id/menu_search"
android:actionLayout="@layout/layout_search"
android:icon="@drawable/search"
android:orderInCategory="0"
android:showAsAction="always|collapseActionView"
android:title="@string/search"/>
</menu>
在您的活动或片段中覆盖 onCreateOptionsMenu 就像这个 fragment.java
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu, menu);
final EditText editText = (EditText) menu.findItem(
R.id.menu_search).getActionView();
editText.addTextChangedListener(textWatcher);
MenuItem menuItem = menu.findItem(R.id.menu_search);
menuItem.setOnActionExpandListener(new OnActionExpandListener() {
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
return true; // Return true to collapse action view
}
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
editText.clearFocus();
return true; // Return true to expand action view
}
});
}
并添加 textWatcherListener
private TextWatcher textWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (null != mAdapter) {
mAdapter.getFilter().filter(s);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
于 2012-11-29T09:34:40.960 回答