1

Я использую MainActivity, полученный из FragmentActivity, с фрагментами, представляющими каждую вкладку в ActionBar. Из документов в http://developer.android.com/guide/topics/ui/actionbar.html я реализовал разбитый ActionBar с вкладками сверху и оставшимися элементами Action в нижней части ActionBar. Поскольку фрагмент каждой вкладки имеет свои собственные конкретные элементы действия, меню, представляющее эти действия, загружается при вызове фрагмента. Это работает вообще. Тем не менее, элементы действия всегда отображаются в меню переполнения в нижней части ActionBar, хотя есть много свободного места. Фактически, никакие видимые элементы или текст не занимают места.Элементы панели действий всегда отображаются в меню переполнения

Я использую библиотеку поддержки v4.

MainActivity

public class MainActivity extends FragmentActivity implements ActionBar.TabListener { 
TabNavigatorPagerAdapter tabNavigatorPagerAdapter; 
ViewPager viewPager; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    // Create the adapter that will return a fragment for each of the three primary sections 
    // of the app 
    tabNavigatorPagerAdapter = new TabNavigatorPagerAdapter(getSupportFragmentManager()); 

    // Set up the action bar 
    final ActionBar actionBar = getActionBar(); 

    // Specify that the Home/Up button should not be enabled, since there is no hierarchical 
    // parent 
    actionBar.setHomeButtonEnabled(false); 

    //force tabs at top and actions at bottom 
    actionBar.setDisplayShowHomeEnabled(false); 
    actionBar.setDisplayShowTitleEnabled(false); 

    // Specify that we will be displaying tabs in the action bar 
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 

    // Set up the ViewPager, attaching the adapter and setting up a listener for when the 
    // user swipes between sections 
    viewPager = (ViewPager) findViewById(R.id.pager); 
    viewPager.setAdapter(tabNavigatorPagerAdapter); 
    viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { 
     @Override 
     public void onPageSelected(int position) { 
      // When swiping between different app sections, select the corresponding tab 
      // We can also use the ActionBar.Tab#select() to do this if we have a reference 
      // to the Tab 
      actionBar.setSelectedNavigationItem(position); 
     } 
    }); 

    // For each of the sections in the app, add a tab to the action bar. 

    // Add Calendar activity 
    actionBar.addTab(actionBar.newTab().setText(R.string.calendar_activity).setTabListener(this)); 
    // Add Grocery List activity 
    actionBar.addTab(actionBar.newTab().setText(R.string.grocery_list_activity).setTabListener(this)); 
    // Add Search activity 
    actionBar.addTab(actionBar.newTab().setText(R.string.search_activity).setTabListener(this)); 
} 

@Override 
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
} 

@Override 
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
    // When the given tab is selected, switch to the corresponding page in the ViewPager. 
    viewPager.setCurrentItem(tab.getPosition()); 
} 

@Override 
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { 
} 

public static class TabNavigatorPagerAdapter extends FragmentPagerAdapter { 
    public TabNavigatorPagerAdapter(android.support.v4.app.FragmentManager fm) { 
     super(fm); 
    } 

    @Override 
    public Fragment getItem(int i) { 
     switch (i) { 
      case 0: 
       // This is the Calendar section of the App 
       return new CalendarFragment(); 
      default: 
       // The other sections of the app are dummy placeholders 
       Fragment fragment = new DummySectionFragment(); 
       Bundle args = new Bundle(); 
       args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1); 
       fragment.setArguments(args); 
       return fragment; 
     } 
    } 

    @Override 
    public int getCount() { 
     return 3; 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     return "Section " + (position + 1); 
    } 
} 

// The Calendar fragment 
public static class CalendarFragment extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 

     View rootView = inflater.inflate(R.layout.fragment_calendar, container, false); 
     Bundle args = getArguments(); 
     ((TextView) rootView.findViewById(android.R.id.text1)).setText(R.string.calendar_activity); 
     setHasOptionsMenu(true); 

     return rootView; 
    } 

    @Override 
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
     super.onCreateOptionsMenu(menu, inflater); 
     menu.clear(); 
     inflater.inflate(R.menu.menu_calendar, menu); 
    } 
} 
} 

Manifest

<?xml version="1.0" encoding="utf-8"?> 

<uses-sdk android:minSdkVersion="11" /> 

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@android:style/Theme.Holo.Light.DarkActionBar"> 

    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" 
     android:uiOptions="splitActionBarWhenNarrow"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
     <meta-data android:name="android.support.UI_OPTIONS" 
      android:value="splitActionBarWhenNarrow"/> 
    </activity> 
    <activity 
     android:name=".CollectionDemoActivity" 
     android:label="@string/demo_collection"> 

    </activity> 
</application> 

меню Календарь XML

<?xml version="1.0" encoding="utf-8"?> 
<menu xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:myfirstapp="http://schemas.android.com/apk/res-auto" 
xmlns:tools="http://schemas.android.com/tools" 
tools:context="com.kikicorp.myfirstapp.MainActivity"> 
<item 
    android:id="@+id/qwe" 
    android:icon="@drawable/ic_launcher" 
    myfirstapp:showAsAction="ifRoom" 
    android:title="qwe"> 
</item> 
<item 
    android:id="@+id/ee" 
    android:icon="@drawable/ic_action_edit" 
    myfirstapp:showAsAction="ifRoom" 
    android:title="edit"> 
</item> 
<item 
    android:id="@+id/xx" 
    android:icon="@drawable/ic_action_new" 
    myfirstapp:showAsAction="ifRoom" 
    android:title="new"> 
</item> 
<item 
    android:id="@+id/go_crazy" 
    android:icon="@drawable/ic_action_search" 
    myfirstapp:showAsAction="ifRoom" 
    android:title="@string/go_crazy_action"> 
</item> 
</menu> 

скриншот Результата

enter image description here

ответ

1

Вы используете панель нативные действий, как указано на то, что вы наследуемые от FragmentActivity, не ActionBarActivity. Следовательно, myfirstapp:showAsAction будет проигнорирован. Используйте android:showAsAction для собственной панели действий.

Если вы намереваетесь использовать appcompat-v7 для заднего плана действия, то измените свой класс на наследование с ActionBarActivity, а не FragmentActivity.

+0

Когда я использую android: showAsAction, Android Studio IDE отмечает это как ошибку, советуя ссылаться на мое собственное пространство имен, в этом случае myfirstapp. Когда я игнорирую его и запускаю приложение, он работает точно так, как я хочу. Спасибо за решение этой проблемы! Слишком плохо IDE дал мне неправильный совет ... – Gnagy

+0

Я использую myfirstapp: showAsAction, appcompat-v7, наследует от ActionBarActivity, и я вижу, что меню переполнения похоже на изображение. Как я могу заставить отобразить меню переполнения в верхней панели? – MARM

+0

@MARM: Удалите 'splitActionBarWhenNarrow' из вашего манифеста. Это не должно работать с современными версиями 'appcompat-v7' в любом случае, последний раз я проверил. – CommonsWare

Смежные вопросы