Определенный пользователем ActionBar Action View: получение ширины справа
Сэндвич с мороженым:
Я хочу добавить AutoCompleteTextView в ActionBar через стандартный механизм Action View (поскольку SearchView недоступен до ICS, и я также использую ActionBarSherlock)
<item android:id="@+id/menu_search" android:actionViewClass="com.example.AutoCompleteActionView" android:showAsAction="ifRoom" android:title="@string/address"></item>
<item android:id="@+id/menu_close" android:icon="@drawable/ic_menu_close_clear_cancel" android:showAsAction="always"></item>
<item android:id="@+id/menu_ok" android:icon="@drawable/ic_menu_ok" android:showAsAction="always"></item>
Это работает, однако по умолчанию он не использует доступное пространство в ActionBar, которое мне бы хотелось.
Я посмотрел источник для SearchView и увидел, как он переопределяет onMeasure, и сделал то же самое для моего собственного класса, который я получил из AutoCompleteTextView. Когда я это делаю, AutoCompleteTextView потребляет все пространство, не оставляя места для двух элементов меню, которые я хочу отображать справа от него.
Похоже, что ширина, возвращаемая из MeasureSpec.getSize(), не учитывает два других пункта меню, когда MeasureSpec.getMode() MeasureSpec.AT_MOST.
Кто-нибудь сделал что-нибудь подобное? Любые предложения?
Спасибо, Damian
Ответы
Ответ 1
Я думаю, что это могло бы помочь:
Создайте складной элемент меню с настраиваемой компоновкой:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menuSearch"
android:showAsAction="always|collapseActionView" android:icon="@drawable/action_search" android:actionLayout="@layout/collapsible_absearch">
</item>
</menu>
Это настраиваемый макет:
<?xml version="1.0" encoding="utf-8"?>
<AutoCompleteTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ab_Search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/search" />
Затем в вашей деятельности:
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activitymenu, menu);
MenuItem menuItem=menu.findItem(R.id.menuSearch);
menuItem.setOnActionExpandListener(new OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
mAbSearch=(AutoCompleteTextView) item.getActionView().findViewById(R.id.ab_Search);
// Set your adapter and do whatever you want
return true;
}
});
Ответ 2
Мне не удалось заставить предложение Маттиаса работать в коде (возможно, я чего-то пропустил), но добавление атрибута minWidth к самому верхнему элементу моего Action View сделало трюк.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="64dip"
android:minWidth="64dip"
android:layout_height="match_parent"
android:gravity="center" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/imageViewAnimatedProgressSpinner"
android:background="@drawable/animated_progress_spinner" />
</FrameLayout>
Ответ 3
Это поможет вам:
ActionBar.LayoutParams layoutParams = new LayoutParams(android.app.ActionBar.LayoutParams.MATCH_PARENT, android.app.ActionBar.LayoutParams.MATCH_PARENT);
View customNav = LayoutInflater.from(getSupportActionBar().getThemedContext()).inflate(R.layout.your_layout, null);
getSupportActionBar().setCustomView(customNav, layoutParams);
getSupportActionBar().setDisplayShowCustomEnabled(true);
Ответ 4
может быть светлее, но если кто-то ищет, сделайте следующее в своих действиях, чтобы получить их в виде значков в панели действий по умолчанию,
//Define a style which extends the themed action button in styles.xml, if you want you can use references to have dynamic styles.. this is an example for holo theme
<style name="ActionButtonStyle" parent="@android:style/Widget.Holo.ActionButton">
</style>
//For your action view, use this as the style, I find the issue with Progress bars and hence //the example,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
style="@style/ActionButtonStyle" >
<ProgressBar
android:id="@+id/progressBar2"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ProgressBar>
</LinearLayout>
Ответ 5
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/visibility_search_edit_text"/>
</RelativeLayout>
Подпишитесь на это сообщение: Сделайте ширину ActionView для Android ActionBar соответствующей ширине ActionBar. Это сделает его растянутым.