根据ViewPager Android显示菜单项

时间:2015-02-05 10:58:35

标签: android android-actionbar android-viewpager menu-items

我的Android应用中有一个包含片段的ViewPager。我想根据ViewPager的片段显示Action Bar菜单项。我已经对此提出了一些问题,但我找不到正确的解决方案。我的ViewPager代码是这样的:

    public class My_Activity extends ActionBarActivity  {

        private ViewPager mViewPager;
        String idioma;


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


            ActionBar actionBar = getSupportActionBar(); // || getActionBar();
            actionBar.setIcon(getResources().getDrawable(R.drawable.navbar_logo));
            actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#CC3333")));

            actionBar.setTitle("Hello");



             mViewPager = (ViewPager) findViewById(R.id.viewpager);
             PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pagerTabStrip);
             pagerTabStrip.setTabIndicatorColor(getResources().getColor(R.color.blanco));


             Title_Liga_Adapter titleAdapter = new Title_Liga_Adapter(getSupportFragmentManager());
             mViewPager.setAdapter(titleAdapter);

             mViewPager.setCurrentItem(0);

             getSupportActionBar().setIcon(R.drawable.navbar_logo);

             getSupportActionBar().setDisplayHomeAsUpEnabled(true);


            }


     @Override
public boolean onCreateOptionsMenu(Menu menu) {
if (mViewPager.getCurrentItem()==4){
    getMenuInflater().inflate(R.menu.menu_comunidad, menu);
}
else{

}
      return true;  
}


/* *
 * Called when invalidateOptionsMenu() is triggered
 */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {

    menu.findItem(R.id.action_search).setVisible(true);


    return super.onPrepareOptionsMenu(menu);
}

 public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
           this.finish();
           return true;

        case R.id.action_search:

            return true;

         default:
                return super.onOptionsItemSelected(item);
            }
    }


    }

我希望当CurrentItem为4时,例如显示菜单项图标。

4 个答案:

答案 0 :(得分:7)

首先在 onCreate 方法中创建 addOnPageChangeListener

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

    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            invalidateOptionsMenu();
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
}

然后重写onCreateOptionMenu()

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    if (mViewPager.getCurrentItem()==0){
        menu.findItem(R.id.action_search).setVisible(true);
    } else if(mViewPager.getCurrentItem()==1){
        menu.findItem(R.id.action_search).setVisible(false);
    } else if(mViewPager.getCurrentItem()==2){
        // configure
    } else if(mViewPager.getCurrentItem()==3){
        // configure
    }
    return super.onCreateOptionsMenu(menu);
}

答案 1 :(得分:1)

确定..您将必须使用ViewPager.OnPageChangeListener来监控onPageSelected()的方法,只要您更改ViewPager的页面,就会触发该方法。您必须跟踪当前页面的内容,并在每次调用onPageSelected()时调用ActivityCompat.invalidateOptionsMenu invalidateOptionsMenu()是使其工作的关键,它将负责触发“刷新”。选项菜单..将间接调用onCreateOptionsMenu()方法将被调用,你有机会隐藏'或者'显示'根据所选标签的不同项目集。

例如:

public boolean onCreateOptionsMenu(Menu menu) {
   ///

   if (currentPageIdx == 4) {
      // inflate menu for page 4
      // configure the menus
   } ....


  return super.onCreateOptionsMenu(menu);
}

答案 2 :(得分:1)

我回答我自己的问题:

@Override
        public boolean onCreateOptionsMenu(Menu menu) {

            getMenuInflater().inflate(R.menu.menu_comunidad, menu);

              return true;  
        }


        /* *
         * Called when invalidateOptionsMenu() is triggered
         */
        @Override
        public boolean onPrepareOptionsMenu(Menu menu) {
            if (mViewPager.getCurrentItem()==4){
            menu.findItem(R.id.action_search).setVisible(true);
            }
            else{
                menu.findItem(R.id.action_search).setVisible(false);
            }
            return super.onPrepareOptionsMenu(menu);
        }

         public boolean onOptionsItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                // Respond to the action bar's Up/Home button
                case android.R.id.home:
                   this.finish();
                   return true;

                case R.id.action_search:

                    return true;

                 default:
                        return super.onOptionsItemSelected(item);
                    }
            }

答案 3 :(得分:0)

活动菜单

设置主菜单,但不包括与片段相关的菜单项。 即。

<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="300"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_help"
        android:title="@string/action_help"
        android:orderInCategory="400"
        app:showAsAction="never"
        android:visible="true"/>
</menu>

“第一片段”菜单(我的是资产列表)

<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_add_asset"
        android:title="@string/add_new_asset"
        android:orderInCategory="100"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_edit_asset_type"
        android:title="@string/edit_asset_types"
        android:orderInCategory="200"
        app:showAsAction="never" />

</menu>

第二片段菜单(负债)

<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_add_liability"
        android:title="@string/add_new_liability"
        android:orderInCategory="100"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_edit_liability_type"
        android:title="@string/edit_liability_types"
        android:orderInCategory="200"
        app:showAsAction="never" />
</menu>

片段代码(两者)

在每个片段的onActivityCreated中:

  setHasOptionsMenu(true);

片段1代码

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    super.onCreateOptionsMenu(menu, inflater)

    try {
        inflater.inflate(R.menu.menu_asset, menu)
    } catch (e: NullPointerException) {
        e.printStackTrace()
    }
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    val id = item.itemId

    if (id == R.id.action_add_asset) {
        startNewActivity(NewAssetActivity::class.java)
        return true
    } else if (id == R.id.action_edit_asset_type) {
        startNewActivity(AssetTypeActivity::class.java)
        return true
    }
    return false
}

片段2代码

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    super.onCreateOptionsMenu(menu, inflater)

    try {
        inflater.inflate(R.menu.menu_liability, menu)
    } catch (e: NullPointerException) {
        e.printStackTrace()
    }
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    val id = item.itemId

    if (id == R.id.action_add_liability) {
        startNewActivity(NewLiabilityActivity::class.java)
        return true
    } else if (id == R.id.action_edit_liability_type) {
        startNewActivity(LiabilityTypeActivity::class.java)
        return true
    }
    return false
}

使用查看寻呼机在片段之间滑动时,菜单将自动更改。

使用orderInCategory来显示菜单的正确顺序。

不需要其他任何东西,您不需要隐藏/显示任何东西。