根据所选的选项卡显示和隐藏ActionBar中的项目

时间:2015-11-13 13:36:06

标签: android android-fragments android-activity android-actionbar android-menu

我需要获取所选标签的数字位置,以显示/隐藏MainActivity中的ActionBar项目。例如,我在Tab1中显示用于编写新邮件的项目,进入Tab2,隐藏新邮件项目并显示用于将用户添加到地址簿的项目... 应用程序的结构是:MainActivity with Tab Layout(4个Tabs),FragmentStatePagerAdapter管理所有碎片。

MainActivity

Default Value or Binding as a (NULL)

ViewPagerAdapter

public class MainActivity extends AppCompatActivity {

// Declaring Your View and Variables

Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"1","2","3","4"};
int Numboftabs =4;

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

    // Creating The Toolbar and setting it as the Toolbar for the activity

    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    //setSupportActionBar(toolbar);

    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);

    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return ContextCompat.getColor(getApplicationContext(), R.color.darkgreen);
        }
    });

    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);

}

@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);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    switch (id) {
        case R.id.action_settings:
            Intent intentMSett = new Intent(this, MainSettings.class);
            startActivity(intentMSett);
            break;
        case R.id.action_add_user:
            Intent intent = new Intent(this, CreateUser.class);
            startActivityForResult(intent, 101);
            break;
        case R.id.action_search:
            Toast.makeText(getApplicationContext(),
                    "search", Toast.LENGTH_SHORT).show();
            break;
    }

    return super.onOptionsItemSelected(item);
}

}

搜索解决方案我已经为MainActivity找到了这种方法:

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
private Context context;

// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
    super(fm);

    this.Titles = mTitles;
    this.NumbOfTabs = mNumbOfTabsumb;

}

//This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int position) {

    if(position == 0) // if the position is 0 we are returning the First tab
    {
        Tab1 tab1 = new Tab1();
        return tab1;
    } else if(position == 1){
        Tab2 tab2 = new Tab2();
        return tab2;
    } else if(position == 2) {
        Tab3 tab3 = new Tab3();
        return tab3;
    } else if(position == 3) {
        Tab4 tab4 = new Tab4();
        return tab4;
    } else {
        Tab1 tab1 = new Tab1();
        return tab1;
    }
}

// This method return the titles for the Tabs in the Tab Strip

@Override
public CharSequence getPageTitle(int position) {

    return Titles[position];
}

// This method return the Number of tabs for the tabs Strip

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

SlidingTabLayout

 @Override
 public boolean onPrepareOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    MenuInflater inflater = getMenuInflater();
    int currentTab = tabHost.getCurrentTab();
    Toast.makeText(getApplicationContext(), currentTab+"", Toast.LENGTH_SHORT);
    menu.clear();
    if (currentTab == 0) {
        inflater.inflate(R.menu.first, menu);  //  menu for photospec.
    } else {
        inflater.inflate(R.menu.second, menu);  // menu for songspec
    }
    return super.onPrepareOptionsMenu(menu);
}

但是我不知道如何设置getCurrentTab()以获取Tab位置,而不是在ViewPagerAdapter我的位置,但我不知道如何从MainActivity获取菜单。溶液

3 个答案:

答案 0 :(得分:2)

您可以使用setHasOptionMenu(Boolean);

执行此操作

然后在你的onCreateOptionsMenu()中创建图标和标题,这是一个例子:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  super.onCreateOptionsMenu(menu, inflater);
  inflater.inflate(R.menu.your_fragment_menu, menu);
  //add the items here.
}

另请查看此example

修改

在每个片段上,你可以给菜单充气,因为我说你创建了两个菜单,所以在onCreateOptionsMenu()上的一个片段中添加第一个片段,第二个片段添加第二个片段,以及如此。

答案 1 :(得分:2)

步骤1:创建一个包含所有操作栏项的菜单资源。如有必要,请在资源中有一个或多个android:visible="false"

步骤2:在onPrepareOptionsMenu()中,在充气资源后调用findItem() on the Menu,以检索状态不同的MenuItem个对象。在活动的领域抓住这些。

步骤3:向ViewPager添加OnPageChangeListener,并根据需要在setVisibility()个对象上调用MenuItem,以便在用户选择不同标签时更改其状态。最有可能的是,这需要更改您从SlidingTabLayout获取的地方,因为它可能设置OnPageChangeListener,并且每ViewPager只能有一个。{/ p>

答案 2 :(得分:0)

我已经解决了在MainActivity中添加OnPageChangeListener的方法,我发布了更新后的代码:

<强> MainActivity

public class MainActivity extends AppCompatActivity {

// Declaring Your View and Variables

Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"1","2","3","4"};
int Numboftabs =4;
Integer tabSelected = 1;

public static Integer MYACTIVITY_REQUEST_CODE = 101;

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

    //
    // Creating The Toolbar and setting it as the Toolbar for the activity

    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    //setSupportActionBar(toolbar);

    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);

    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return ContextCompat.getColor(getApplicationContext(), R.color.darkgreen);
        }
    });

    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);

}


@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    tabSelected = getCurrentTab();

    switch (tabSelected) {
        case 1:
            //other..
            break;
        case 2:
            //other..
            break;
        case 3:
            MenuItem addUser = menu.findItem(R.id.action_add_user);
            addUser.setVisible(true);
            break;
        case 4:
            MenuItem message = menu.findItem(R.id.action_message);
            message.setVisible(true);
            break;
    }
    return super.onPrepareOptionsMenu(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.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    switch (id) {
        case R.id.action_settings:
            Intent intentMSett = new Intent(this, MainSettings.class);
            startActivity(intentMSett);
            break;
        case R.id.action_add_user:
            Intent intentCUser = new Intent(this, CreateUser.class);
            startActivityForResult(intentCUser, 101);
            break;
        case R.id.action_message:
            Intent intentMessage = new Intent(this, CreateMessage.class);
            startActivityForResult(intentMessage, 102);
            break;
    }

    return super.onOptionsItemSelected(item);
}


public Integer getCurrentTab(){
    pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            switch (position) {
                case 0:
                    tabSelected = 1;
                    break;
                case 1:
                    tabSelected = 2;
                    break;
                case 2:
                    tabSelected = 3;
                    break;
                case 3:
                    tabSelected = 4;
                    break;
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
    return tabSelected;
}

}