Android项目中,对于Tab+Swipe应用程序的不同标签页需要有不同的菜单。

11

我是一个初学者,对于Android应用程序和Java基本上只了解PHP开发。

我有一个Tab加Swipe的应用程序项目。

Reseller.java

Reseller.java是一个Java类文件的名称,具体内容需要查看代码才能确定。

package com.idevoc.onsitereseller;

import java.util.ArrayList;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuInflater;

public class Reseller extends FragmentActivity {

    FragmentTransaction transaction;
    static ViewPager mViewPager;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_reseller);

    Fragment tabOneFragment = new TabOne();
    Fragment tabTwoFragment = new TabTwo();

    PagerAdapter mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
    mPagerAdapter.addFragment(tabOneFragment);
    mPagerAdapter.addFragment(tabTwoFragment);

    //transaction = getSupportFragmentManager().beginTransaction();

    mViewPager = (ViewPager) findViewById(R.id.pager);
            mViewPager.setAdapter(mPagerAdapter);
            mViewPager.setOffscreenPageLimit(2);
        mViewPager.setCurrentItem(0);

            mViewPager.setOnPageChangeListener(
                new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        // When swiping between pages, select the
                        // corresponding tab.
                        getActionBar().setSelectedNavigationItem(position);
                    }
                });

    ActionBar ab = getActionBar();
    ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    Tab tab1 = ab.newTab().setText("Tab One")
                    .setTabListener(new TabListener<TabOne>(
                    this, "tabone", TabOne.class));

            Tab tab2 = ab.newTab().setText("Tab Two")
                            .setTabListener(new TabListener<TabTwo>(
                    this, "tabtwo", TabTwo.class));

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
    return true;
}

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) {
        // User selected the already selected tab. Usually do nothing.
    }

            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);
    }
  }

 }

TabOne.java

 package com.idevoc.onsitereseller;

 import android.os.Bundle;
 import android.support.v4.app.Fragment;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;

public class TabOne extends Fragment
{
public static final String ARG_SECTION_NUMBER = "section_number";
     @Override
    public void onActivityCreated(Bundle savedInstanceState) {
       super.onActivityCreated(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState)
    {
            View view = inflater.inflate(R.layout.tab_a, container, false);
            return view;
    }

}

TabTwo.java

 package com.idevoc.onsitereseller;

 import android.os.Bundle;
 import android.support.v4.app.Fragment;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;

 public class TabTwo extends Fragment
 {

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState)
    {
            View view = inflater.inflate(R.layout.tab_a, container, false);

            return view;
    }
  }

我在加载应用程序的两个选项卡并加载一个公共菜单,但我需要为不同的选项卡加载不同的菜单,例如:

如果选项卡是TabOne,则加载menu_a;如果选项卡是TabTwo,则加载具有不同选项的menu_b。我不想加载公共菜单。我该如何做到这一点?

2个回答

24

在 res/menu 文件夹中为 menu_a.xml 和 menu_b.xml 创建一个菜单 XML 文件。

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_item_search"
        android:icon="@drawable/ic_action_search"
        android:title="@string/description_search"
        android:orderInCategory="1"
        android:showAsAction="ifRoom" />
    <item android:id="@+id/menu_item_share"
        android:icon="@drawable/ic_action_share"
        android:title="@string/description_share"
        android:orderInCategory="1"
        android:showAsAction="ifRoom" />
</menu>
为了为当前Fragment创建一个选项菜单,请在Fragment的onCreate()方法中添加setHasOptionsMenu(true)。
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setHasOptionsMenu(true);

}

接下来,您需要通过覆盖onCreateOptionsMenu()方法来展开相应的选项菜单(menu_a.xml或menu_b.xml)。

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

要处理菜单选择,请覆盖onOptionsItemSelected()

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.menu_item_search:                
              //do something
            return true;

        case R.id.menu_item_share:
              //do something
            return true;
    }
    return super.onOptionsItemSelected(item);
} 

请查看 创建选项菜单:http://developer.android.com/guide/topics/ui/menus.html 以获取更多详细信息。


如何使用效果来实现这个? - bernzkie
@bernzkie 什么样的效果? - TouchBoarder
第一个菜单图标会淡出,然后第二个会淡入吗?如果可能的话? - bernzkie
@bernzkie 如果是这样的话,我会尝试在父活动中添加菜单项,保留对菜单项的引用,并在选项卡或页面更改侦听器中以编程方式切换菜单图标。这可能会有所帮助 https://dev59.com/j5Lea4cB1Zd3GeqPxxYP#34295265 - TouchBoarder
1
@Saifee 确保您只填充特定于 Fragment 的 menu.xml,不要填充父 Activity 中的任何菜单。如果这样做,Fragment 菜单将添加到您的 Activity 菜单中。 - TouchBoarder
显示剩余3条评论

1

是的,我用这些代码得到了输出结果,

在TabOne.java和TabTwo.java中,我已经添加了。

   setHasOptionsMenu(true);

在onCreateView()函数中,然后是具有不同菜单的menu函数,从主类中删除了menu函数。
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState)
    {
            View view = inflater.inflate(R.layout.tab_a, container, false);
            setHasOptionsMenu(true);
            return view;
    }
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        //super.onCreateOptionsMenu(menu, inflater);
         inflater.inflate(R.menu.menu_b, menu);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接