Меню опций Android должно оставаться, даже когда мы нажимаем на меню настроек ниже

1

Я создал меню опций в android. Я написал код для отображения меню, когда начинается действие. Но проблема в том, что меню опций исчезнет, когда я нажму на меню настроек под ним. Я хочу, чтобы меню опций сохранялось на моей странице меню, даже когда я нажимаю на страницу активности или параметры предпочтений на странице. Пожалуйста, помогите.

Вот мой xml-код:

  <menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/icon"
    android:icon="@drawable/icon" />
  <item android:id="@+id/text"
    android:title="Text" />
  <item android:id="@+id/icontext"
    android:title="Icon and text"
    android:icon="@drawable/icon" />
  </menu>

Код Java:

 public void onAttachedToWindow()
  { 
    super.onAttachedToWindow();  
    openOptionsMenu(); 
  } 

 @Override
 public boolean onCreateOptionsMenu(Menu menu)
 {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
  }
  • 0
    Это стандартное поведение меню. Почему бы вам не использовать ListView или некоторые другие компоненты в Activity.
Теги:
android-optionsmenu

3 ответа

1
Лучший ответ

У вас есть несколько вариантов, если вы хотите иметь постоянные кнопки в нижней части экрана. Вы можете поместить LinearLayout внизу или использовать RelativeLayout с alignParentBottom=true. Во всяком случае, OptionsMenu должен OptionsMenu только на клавише опций и закрываться на опциях. Нажмите или нажмите клавишу. Любая другая реализация связана с пользовательским интерфейсом Android.

Вот (часть) страницы prefs, которую я создал с различными параметрами в scrollview, и кнопку сохранения внизу:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/titleTextView"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_alignParentTop="true"
        android:background="@drawable/background_blue_gradient"
        android:gravity="center"
        android:text="Preferences"
        android:textColor="@color/white"
        android:textSize="16dp"
        android:textStyle="bold" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/preferencesSaveButton"
        android:layout_below="@id/titleTextView" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/titleTextView"
                android:paddingBottom="0dp"
                android:paddingLeft="10dp"
                android:paddingRight="10dp"
                android:paddingTop="10dp"
                android:weightSum="2" >

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_weight="1.2"
                    android:text="Activate Notifications" />

                <View
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="0.2" />

                <ToggleButton
                    android:id="@+id/allowAlertsToggleButton"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_weight="0.6"
                    android:textOff="No"
                    android:textOn="Yes" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingBottom="0dp"
                android:paddingLeft="10dp"
                android:paddingRight="10dp"
                android:paddingTop="10dp"
                android:weightSum="2" >

                <TextView
                    android:id="@+id/alertDelayTextView"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_weight="0.8"
                    android:text="Notifications Delay" />

                <View
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="0.2" />

                <Spinner
                    android:id="@+id/alertDelaySpinner"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_weight="1"
                    android:entries="@array/alert_intervals" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingBottom="0dp"
                android:paddingLeft="10dp"
                android:paddingRight="10dp"
                android:paddingTop="10dp" >

                <CheckBox
                    android:id="@+id/allowAutostartCheckBox"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical" />

                <View
                    android:layout_width="20dp"
                    android:layout_height="wrap_content" />

                <TextView
                    android:id="@+id/allowAutostartTextView"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:text="Auto start on boot" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

    <Button
        android:id="@id/preferencesSaveButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="10dp"
        android:padding="15dp"
        android:text="Save"
        android:textStyle="bold" />

</RelativeLayout>
  • 0
    Не могли бы вы показать мне пример макета страницы XML
  • 0
    См. Мое редактирование выше
Показать ещё 2 комментария
1
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;

Используйте этот код в методе oncreate.

  • 0
    Я получаю ошибки, когда я вставляю его в oncreate
  • 0
    какие ошибки?
0

Вы должны использовать обычный вид: горизонтальный LinearLayout с и заполнять его кнопками вместо использования MenuOptions.

Если это на HoneyComb или ICS, вы можете использовать следующий флаг в Menu.xml, это отобразит параметры меню и действия в панели действий

<item android:id="@[+][package:]id/resource_name"
      android:title="string"
      android:titleCondensed="string"
      android:icon="@[package:]drawable/drawable_resource_name"
      android:onClick="method name"
      android:showAsAction= "always"    
      ..
 /> 
  • 0
    Спасибо Rajdeep: я подумал, если я выберу ваш горизонтальный метод LinearLayout, возможно ли, что кнопки будут перемещаться по активности страницы предпочтений
  • 0
    не уверен, что вы подразумеваете под поплавком?

Ещё вопросы

Сообщество Overcoder
Наверх
Меню