Значок "Центр" в панели действий Android
Я пытаюсь центрировать значок в панели действий Android. Я использую пользовательский макет с кнопкой слева, значок в центре и параметры меню справа.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ActionBarWrapper"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageButton
android:id="@+id/slideMenuButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_menu_bookmark" />
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true" >
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:layout_centerInParent="true" />
</RelativeLayout>
</RelativeLayout>
Я пробовал это с помощью и без RelativeLayout, который обертывал ImageView. Левая кнопка отображается хорошо, и я могу установить значок с layout_toRightOf, но я не могу получить его в центр. У кого-нибудь есть идеи?
Изменить:
Здесь код android в методе create on.
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayOptions(actionBar.DISPLAY_SHOW_CUSTOM);
View cView = getLayoutInflater().inflate(R.layout.actionbar, null);
actionBar.setCustomView(cView);
Ответы
Ответ 1
Хорошо. Это должно сработать. Попробуйте это (Протестировано в нормальной деятельности):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ActionBarWrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<ImageButton
android:id="@+id/slideMenuButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:layout_alignParentLeft="true" />
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:layout_centerVertical="true"
android:layout_centerInParent="true" />
</RelativeLayout>
Ответ 2
Предыдущие ответы не работают для меня (на устройствах Android 4.4), потому что внешние группы просмотра контейнеров не были полностью расширены, поэтому группа контейнеров и центрированный внутренний логотип уже были выровнены в строке заголовка.
Я нашел макет, который работает с обычным меню панели действий (с правой стороны) и независимо от включения обычного логотипа панели действий и названия (слева). В этом примере центрируется только дополнительный логотип.
<?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"
android:orientation="horizontal"
>
<View android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_logo"
android:layout_gravity="center_vertical"
android:contentDescription="Logo"
/>
<View android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
Вы должны включить пользовательский просмотр с помощью этого
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowCustomEnabled(true);
View cView = getLayoutInflater().inflate(R.layout.actionbar, null);
actionBar.setCustomView(cView);
но не этот метод (он отключает все остальные элементы в панели действий).
// actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
Ответ 3
Вы можете добавить пользовательский вид в панель действий. Просто добавьте LinearLayout в качестве пользовательского представления и добавьте sub-представления в linearlayout. Я использовал эту технику, чтобы добавить 4 кнопки в середине.
Для добавления пользовательского представления используйте actionBar.setCustomView(view). Также установите опцию DISPLAY_SHOW_CUSTOM с помощью actionBar.setDisplayOptions.
После того, как у вас есть пользовательский вид в панели, используйте обычные процедуры макета, чтобы получить необходимый эффект. Один трюк, который вы могли бы использовать, состоял бы в том, чтобы иметь 3 вложенных линейных макета и назначить каждый вес. Например, 1,4,1, поэтому макет центра занимает больше места. Вот пример, конечно, вы можете оставить кнопки на правой стороне макета, если хотите, чтобы он был пустым. При таком подходе вы можете достичь точного центра.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#F00"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="#0F0"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#00F"
android:gravity="right"
android:orientation="horizontal" >
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
</LinearLayout>