2013-04-23 4 views
0

Я использовал существующую модель меню Tab (панель действий), и теперь у меня проблема с добавлением подменю на каждую вкладку, как я могу это сделать?подменю в ActionBar Tabs android code

это мой код:

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

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

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

    // Set up the ViewPager with the sections adapter. 
    mViewPager = (ViewPager) findViewById(R.id.pager); 
    mViewPager.setAdapter(mSectionsPagerAdapter); 

    // When swiping between different sections, select the corresponding 
    // tab. We can also use ActionBar.Tab#select() to do this if we have 
    // a reference to the Tab. 
    mViewPager 
    .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { 
       @Override 
    public void onPageSelected(int position) { 
         actionBar.setSelectedNavigationItem(position); 
       } 
    }); 
    // For each of the sections in the app, add a tab to the action bar. 
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { 
     // Create a tab with text corresponding to the page title defined by 
     // the adapter. Also specify this Activity object, which implements 
     // the TabListener interface, as the callback (listener) for when 
     // this tab is selected. 
     Tab tab = actionBar.newTab(); 
     tab.setText(mSectionsPagerAdapter.getPageTitle(i)); 
     tab.setTabListener(this);  
     actionBar.addTab(tab); 
    } 
} 

это меню/main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" > 
    <item 
     android:id="@+id/action_settings" 
     android:orderInCategory="100" 
     android:showAsAction="never" 
     android:title="@string/action_settings"> 
    </item> 
</menu> 

вот остальная часть кода:

@Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 


     return true; 
    } 



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

     mViewPager.setCurrentItem(tab.getPosition()); 
    } 

    /** 
* 
*/ 


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

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

    /** 
    * A {@link FragmentPagerAdapter} that returns a fragment corresponding to 
    * one of the sections/tabs/pages. 
    */ 
    public class SectionsPagerAdapter extends FragmentPagerAdapter { 

     public SectionsPagerAdapter(FragmentManager fm) { 
      super(fm); 
     } 

     @Override 
     public Fragment getItem(int position) { 
      // getItem is called to instantiate the fragment for the given page. 
      // Return a DummySectionFragment (defined as a static inner class 
      // below) with the page number as its lone argument. 
      Fragment fragment = new DummySectionFragment(); 
      Bundle args = new Bundle(); 
      args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1); 
      fragment.setArguments(args); 
      return fragment; 
     } 

     @Override 
     public int getCount() { 
      // Show 3 total pages. 
      return 3; 
     } 

     @Override 
     public CharSequence getPageTitle(int position) { 
      Locale l = Locale.getDefault(); 
      switch (position) { 
      case 0: 
       return getString(R.string.title_section1).toUpperCase(l); 
      case 1: 
       return getString(R.string.title_section2).toUpperCase(l); 
      case 2: 
       return getString(R.string.title_section3).toUpperCase(l); 
      } 
      return null; 
     } 
    } 

    /** 
    * A dummy fragment representing a section of the app, but that simply 
    * displays dummy text. 
    */ 
    public static class DummySectionFragment extends Fragment { 
     /** 
     * The fragment argument representing the section number for this 
     * fragment. 
     */ 
     public static final String ARG_SECTION_NUMBER = "section_number"; 

     public DummySectionFragment() { 
     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
       Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_main_dummy, 
        container, false); 
      TextView dummyTextView = (TextView) rootView 
        .findViewById(R.id.section_label); 
      dummyTextView.setText(Integer.toString(getArguments().getInt(
        ARG_SECTION_NUMBER))); 
      return rootView; 
     } 
    } 

Я жду ваших ответов , спасибо

+0

Что такое проблема ?? Вы должны просто добавить «@Override \t onCreateOptionsMenu (меню Menu) общественное булево { \t \t // TODO Auto-сгенерированный метод STUB \t \t getMenuInflater() надуваться (R.menu.activity_main, меню). \t \t возвращение super.onCreateOptionsMenu (меню); \t} ' –

+0

спасибо за ваш ответ, у меня уже есть этот метод, когда я пытаюсь добавить подменю в это меню, которое он переходит в меню опций, а не в контекстМеню (вкладка «Панель действий»), вы видите, что я имею в виду? – Overflow

+0

Вы можете объяснить больше .. ?? –

ответ

0

Предполагая, что все y наши вкладки, имеющие свои собственные расширяющие фрагменты класса, вы просто включаете:

Редактировать: Я просто видел, что вы ищете подменю. Попробуйте этот учебник: http://www.mysamplecode.com/2011/07/android-options-menu-submenu-group.html и посмотрите на «Опции меню Layout optionmenu.xml»


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

Ваш MainActivity- Класс:

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

    //instantiate Fragments/Tabs 
    Fragment tabonefragment = new TabOneFragment(); 
    Fragment tabtwofragment = new TabTwoFragment(); 

    PagerAdapter mPagerAdapter = new PagerAdapter(getSupportFragmentManager()); 
    mPagerAdapter.addFragment(tabonefragment); 
    mPagerAdapter.addFragment(tabtwofragment); 

    // Set up the ViewPager with the sections adapter. 
    mViewPager = (ViewPager) findViewById(R.id.pager); 
    mViewPager.setAdapter(mSectionsPagerAdapter); 

// When swiping between different sections, select the corresponding 
    // tab. We can also use ActionBar.Tab#select() to do this if we have 
    // a reference to the Tab. 
    mViewPager 
    .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { 
      @Override 
    public void onPageSelected(int position) { 
        actionBar.setSelectedNavigationItem(position); 
      } 
    }); 


    //adding tabs to your action bar 
    ActionBar ab = getActionBar(); 
    ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 
    Tab tab1 = ab.newTab().setText("tabonetext") 
      .setTabListener(new TabListener<TabOneFragment>(
        this, "tab_one", TabOneFragment.class)); 

    Tab tab2 = ab.newTab().setText("tabtwotext") 
      .setTabListener(new TabListener<TabTwoFragment>(
        this, "tab_two", TabTwoFragment.class)); 

    ab.addTab(tab1); 
    ab.addTab(tab2); 
    } 

public static class TabListener<T extends Fragment> implements ActionBar.TabListener { 
    private Fragment mFragment; 
    private final Activity mActivity; 
    private final String mTag; 
    private final Class<T> mClass; 

    /** Constructor used each time a new tab is created. 
     * @param activity The host Activity, used to instantiate the fragment 
     * @param tag The identifier tag for the fragment 
     * @param clz The fragment's Class, used to instantiate the fragment 
     */ 
    public TabListener(Activity activity, String tag, Class<T> clz) { 
     mActivity = activity; 
     mTag = tag; 
     mClass = clz; 
    } 

    /* The following are each of the ActionBar.TabListener callbacks */ 

    public void onTabSelected(Tab tab, FragmentTransaction ft) { 
     // Check if the fragment is already initialized 
     if (mFragment == null) { 
      // If not, instantiate and add it to the activity 
      mFragment = Fragment.instantiate(mActivity, mClass.getName()); 
      ft.add(android.R.id.content, mFragment, mTag); 
     } else { 
      // If it exists, simply attach it in order to show it 
      ft.attach(mFragment); 
     } 
    } 

    public void onTabUnselected(Tab tab, FragmentTransaction ft) { 
     if (mFragment != null) { 
      // Detach the fragment, because another one is being attached 
      ft.detach(mFragment); 
     } 
    } 

    public void onTabReselected(Tab tab, FragmentTransaction ft) { 
    } 

    public void onTabReselected(Tab arg0, 
      android.app.FragmentTransaction arg1) 
    { 
    } 

    public void onTabSelected(Tab arg0, android.app.FragmentTransaction arg1) 
    { 
     mViewPager.setCurrentItem(arg0.getPosition()); 
    } 

    public void onTabUnselected(Tab arg0, 
      android.app.FragmentTransaction arg1) 
    {   
    } 
} 

public class PagerAdapter extends FragmentPagerAdapter { 

     private final ArrayList<Fragment> mFragments = new ArrayList<Fragment>(); 

     public PagerAdapter(FragmentManager manager) { 
      super(manager); 
     } 

     public void addFragment(Fragment fragment) { 
      mFragments.add(fragment); 
      notifyDataSetChanged(); 
     } 

     @Override 
     public int getCount() { 
      return mFragments.size(); 
     } 

     @Override 
     public Fragment getItem(int position) { 
      return mFragments.get(position); 
     } 
    } 

Ваш Fragment класс:

public class TabOneFragment extends Fragment { 

@Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
    super.onActivityCreated(savedInstanceState); 
    } 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) 
{ 
      //inflate your layout from a tab_one_layout.xml file (or use the same xml of your R.layout.activitiy_main if you want) 
    View view = inflater.inflate(R.layout.tab_one_layout, container, false); 


    return view; 
} 

} 


//HERE: individual options menu of TabOne 
@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.yourmenu, menu); 
    this.menu = menu; 
    //create some submenu if you want 


    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle item selection 

} 

Это должно сделать. Тот же/похожий код также для TabTwo ofc.

+0

. Пожалуйста, проверьте остальную часть кода, которую я добавил, потому что мое меню построено с кодом, а не xml! – Overflow

+0

Умм, я не вижу, где вы создали меню с кодом: 0. Во всяком случае, вы попробовали [addSubMenu-method] (http://developer.android.com/reference/android/view/Menu.html#addSubMenu%28int,%20int,%20int,%20java.lang.CharSequence%29) ?Как SubMenu submenu = yourmainmenu.addSubMenu (...)? – DuKes0mE

+0

Вкладки создаются здесь: \t // Для каждого из разделов приложения добавьте вкладку в панель действий. \t \t для (INT I = 0; я Overflow

0

Я думаю, что я должен изменить этот код:

public static class DummySectionFragment extends Fragment { 
     /** 
     * The fragment argument representing the section number for this 
     * fragment. 
     */ 
     public static final String ARG_SECTION_NUMBER = "section_number"; 

     public DummySectionFragment() { 
     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
       Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_main_dummy, 
        container, false); 
      TextView dummyTextView = (TextView) rootView 
        .findViewById(R.id.section_label); 
      dummyTextView.setText(Integer.toString(getArguments().getInt(
        ARG_SECTION_NUMBER))); 
      return rootView; 
     } 
    } 

и файл XML и replacte TextView с меню?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity$DummySectionFragment" > 

    <TextView 
     android:id="@+id/section_label" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 


</RelativeLayout> 
Смежные вопросы