I cannot figure out how to get PreferenceFragment to work correctly. I have a ViewPager hooked up to a FragmentPagerAdapter, with two Fragments that the user can swipe between. I am trying to get the "Settings" menu working, using a PreferenceFragment, but I am unsure what I'm doing wrong. When I tap Settings the view is changed to a blank white screen.
My SettingsFragment class:
public class SettingsFragment extends PreferenceFragment{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
My PagerAdapter class:
public class PagerAdapter extends FragmentPagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Object instantiateItem(ViewGroup container, int position){
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
#Override
public Fragment getItem(int i) {
switch (i) {
// default case is also case 0 to avoid redundant code
default: return new CalculatorFragment();
case 1: return new TapeFragment();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 1: return "Review";
default: return "Calculator";
}
}
public Fragment getRegisteredFragment(int position){
return registeredFragments.get(position);
}
}
My main class which should create the PreferenceFragment when user taps "Settings"
public class MangoCalc extends FragmentActivity implements CalculatorFragment.CalcTapeInterface{
PagerAdapter pagerAdapter;
ViewPager myViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
final ActionBar actionBar = getActionBar();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mango_calc);
pagerAdapter = new PagerAdapter(getFragmentManager());
myViewPager = (ViewPager) findViewById(R.id.main);
myViewPager.setAdapter(pagerAdapter);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
myViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {}
};
for (int i=0; i< pagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(pagerAdapter.getPageTitle(i))
.setTabListener(tabListener));
}
myViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mango_calc, 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();
if (id == R.id.action_settings) {
FragmentManager fm = getFragmentManager();
SettingsFragment settingsFragment = new SettingsFragment();
fm.beginTransaction().replace(R.id.main, settingsFragment).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTapePass(ArrayList<String> data) {
if (data!=null) Log.d("Tape", "Last element got: "+data.get(data.size()-1));
TapeFragment tapeFragment = (TapeFragment) pagerAdapter.getRegisteredFragment(1);
tapeFragment.updateTape(data);
}
}
My preferences.XML
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="#string/lookandfeel">
<ListPreference
android:key="theme_preference"
android:title="#string/theme"
android:summary="#string/summary_theme_preference"
android:entries="#array/entries_theme_preference"
android:entryValues="#array/entryvalues_theme_preference"
android:defaultValue="mango"/>
<SwitchPreference
android:key="keypress_vibration_preference"
android:title="#string/keypress_vibration"
android:summaryOn="#string/summaryon_keypress_vibration_preference"
android:summaryOff="#string/summaryoff_keypress_vibration_preference"
android:switchTextOn="#string/text_keypress_vibration_on"
android:switchTextOff="#string/text_keypress_vibration_off"
android:defaultValue="true" />
</PreferenceCategory>
</PreferenceScreen>
and the XML for the activity:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main"
/>
In your getitem case 1 needs to be listed before the default
Related
I have a fragment and an activity. I want to display name of tags(fragments) but I don't want to show name of application in actionBar.
This is my activity: when I remove an ActionBarActivity I can not use a FragmentManager
public class ObjectListActivity extends ActionBarActivity implements android.support.v7.app.ActionBar.TabListener {
private ViewPager viewPager;
private android.support.v7.app.ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_object_list2);
// View pager for showing many fragments over a single activity
viewPager = (ViewPager) findViewById(R.id.pager);
// Getting fragment manager to control fragments
FragmentManager fragmnetManager = getSupportFragmentManager();
// Setting adapter over view pager
viewPager.setAdapter(new MyAdapter(fragmnetManager));
// Implementing view pager pagechangelistener to navigate between tabs
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
// Setting navigation of tabs to actionbar
actionBar.setSelectedNavigationItem(pos);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
// Getting actionbar
actionBar = getSupportActionBar();
// Setting navigation mode to actionbar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Now adding a new tab to action bar and setting title, icon and
// implementing listener
android.support.v7.app.ActionBar.Tab tab1 = actionBar.newTab();
tab1.setText("Wszytskie");
// tab1.setIcon(R.drawable.ic_launcher);
tab1.setTabListener(this);
android.support.v7.app.ActionBar.Tab tab2 = actionBar.newTab();
tab2.setText("Grupy");
tab2.setTabListener(this);
// Now finally adding all tabs to actionbar
actionBar.addTab(tab1);
actionBar.addTab(tab2);
}
#Override
public void onTabReselected(android.support.v7.app.ActionBar.Tab arg0,
FragmentTransaction arg1) {
}
#Override
public void onTabSelected(android.support.v7.app.ActionBar.Tab tab,
FragmentTransaction arg1) {
// Setting current position of tab to view pager
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.support.v7.app.ActionBar.Tab arg0,
FragmentTransaction arg1) {
}
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
// Getting fragments according to selected position
Fragment fragment = null;
if (i == 0) {
fragment = new FragmentAllObjectActivity();
}
if (i == 1) {
fragment = new FragmentGroupObjectsActivity();
}
// and finally returning fragments
return fragment;
}
#Override
public int getCount() {
// Returning no. of counts of fragments
return 2;
}
}
Inside onTabSelected add the line:
#Override
public void onTabSelected(android.support.v7.app.ActionBar.Tab tab,
FragmentTransaction arg1) {
// Setting current position of tab to view pager
viewPager.setCurrentItem(tab.getPosition());
setTitle(getText(tab.getPosition()));
}
You have to implement a getText() method which return the right text based on the current fragment like:
public String getText(android.support.v7.app.ActionBar.Tab tab){
// if tab == tabType 1 return "Title 1"
// else return "Title 2"
}
Use bellow code in your onCreate method
setTitle("");//it will remove your app name
My main activity has 3 tabs, each one loads a different fragment.
i am trying to pass data from fragment 1 to fragment 3, but it doesnt work
all 3 fragment can be loaded, but the problem is that only 1&2 are loaded when i start the application. so when i run the application and i want to pass a string from fragment 1 to 3 it doesnt work because it doesnt exist yet. how can i change this?
I am using Eventbus (https://github.com/greenrobot/EventBus) for the communication between fragments.
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private TabLayout mTabLayout;
private ViewPager mPager;
private MyPagerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MyPagerAdapter(getSupportFragmentManager());
mToolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mToolbar);
mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mTabLayout.setTabsFromPagerAdapter(mAdapter);
mTabLayout.setupWithViewPager(mPager);
mPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class MyFragment extends Fragment {
public static final java.lang.String ARG_PAGE = "arg_page";
public MyFragment() {
}
public static MyFragment newInstance(int pageNumber) {
MyFragment myFragment = new MyFragment();
Bundle arguments = new Bundle();
arguments.putInt(ARG_PAGE, pageNumber + 1);
myFragment.setArguments(arguments);
return myFragment;
}
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = MainActivity.MyFragment.newInstance(position); //FRAGMENT fragment;
switch (position) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
default:
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) { //set tab names
switch (position) {
case 0:
return "Thread";
case 1:
return "AsyncTask";
case 2:
return "TODO";
}
return null;
}}}
Minimum number of pages you want your adapter to load is set this way
Viewpager.setOffscreenPageLimit(3);
I would like to give my tabs names in my main.xml file. After a lot of searching i still havent found a working solution. if someone can provide a working solution/suggestion for this, all be it programatically or with xml i would be very thankful.
main_activity.java
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private TabLayout mTabLayout;
private ViewPager mPager;
private MyPagerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MyPagerAdapter(getSupportFragmentManager());
mToolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mToolbar);
mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mTabLayout.setTabsFromPagerAdapter(mAdapter);
mTabLayout.setupWithViewPager(mPager);
mPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class MyFragment extends Fragment {
public static final java.lang.String ARG_PAGE = "arg_page";
public MyFragment() {
}
public static MyFragment newInstance(int pageNumber) {
MyFragment myFragment = new MyFragment();
Bundle arguments = new Bundle();
arguments.putInt(ARG_PAGE, pageNumber + 1);
myFragment.setArguments(arguments);
return myFragment;
}
}
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = MainActivity.MyFragment.newInstance(position); //FRAGMENT fragment;
switch (position) {
case 0:
fragment = new Fragment1();
break;
case 1:
fragment = new Fragment2();
break;
case 2:
fragment = new Fragment3();
break;
default:
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return "Fragment " + (position + 1);
}
}
main.xml
<LinearLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.lvlastuin.tabnav.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabGravity="fill"
app:tabMaxWidth="0dp"
app:tabTextAppearance="#style/TextAppearance.Design.Tab"
app:tabSelectedTextColor="#color/colorAccent"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
over ride this method in your pager adapter
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "tab1 name";
case 1:
return "tab2 name";
}
return null;
}
In your MyPagerAdapter class you have a
#Override
public CharSequence getPageTitle(int position) {
return "Fragment " + (position + 1);
}
Which is generally where you set the names of the tabs. So when you instantiate it, just pass a collection of names you'd like to name the tabs
I have searched for like three days for a solution for this. I have tried a lot of methods but I couldn't get it right. (Or maybe I am doing something wrong where).
So, what I am trying to do is change the Activity title to the current tab name, each time I change the tab, the activity title should change too.
So I have a MainActivity where I have 3 Tabs and 3 different fragments for the tabs. Here the MainActivity:
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
private ViewPager mPager;
private SlidingTabLayout mTabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new CustomPagerAdapter(getSupportFragmentManager()));
mTabs = (SlidingTabLayout) findViewById(R.id.tabs);
mTabs.setDistributeEvenly(true);
mTabs.setViewPager(mPager);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Custom ViewPager for the tabs
class CustomPagerAdapter extends FragmentPagerAdapter {
String[] tabsTitles;
String vpPager;
public CustomPagerAdapter(FragmentManager fm) {
super(fm);
tabsTitles = getResources().getStringArray(R.array.tabTitles);
}
#Override
public Fragment getItem(int position) {
//if (position == 0){
// news_fragment news_fragment = new news_fragment();
// return news_fragment;
//}
if (position == 1){
login_fragment login_fragment = new login_fragment();
return login_fragment;
}
else if (position == 2){
about_fragment about_fragment = new about_fragment();
return about_fragment;
}
else {
news_fragment news_fragment = new news_fragment();
return news_fragment;
}
}
#Override
public CharSequence getPageTitle(int position) {
return tabsTitles[position];
}
#Override
public int getCount() {
return 3;
}
}
}
And I am using this SlidingTabLayout
Try this one :
viewpager
.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
actionBar.setTitle(tabsTitles[position]);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int pos) {
// TODO Auto-generated method stub
}
});
When you change activity. Firstlt onCreate method run. So in you onCreate get ActionBar and set its title.
EXAMPLE
ActionBar actionBar = getActionBar();
actionBar.setTitle("title");
Note : Change getActionBar() to getSupportActionBar() if you are using the support library for ActionBar.
Try this one too:
class CustomPagerAdapter extends FragmentPagerAdapter {
....
Toolbar toolbar;
public CustomPagerAdapter(FragmentManager fm, Toolbar toolbar) {
...
this.toolbar = toolbar;
}
#Override
public Fragment getItem(int position) {
toolbar.setTitle(getPageTitle(position));
...
}
...
}
Set a custom action bar in your activity by inflating some layout like(After Oncreate):
android.app.ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
bar.setDisplayShowHomeEnabled(false);
bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
bar.setCustomView(R.layout.homescreen_actionbar);
Take a TextView in your custom layout and in the onresume method of your fragment fetch its id using getactivity(), and set your title and iit will be working fine.
i've used the existing model of Tab menu (the action bar) , and now i'm having problem adding submenu to each tab , how can i do that ?
this is my 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);
}
}
this is menu/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>
here is the rest of code :
#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;
}
}
i'm waiting your answers , thanks
Assuming all your tabs having their own class extending fragments, you simply include:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.yourmenu, menu);
this.menu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
}
Edit: I just saw you are looking for a sub menu. Try this tutorial: http://www.mysamplecode.com/2011/07/android-options-menu-submenu-group.html
and take a look at "Options Menu Layout optionmenu.xml"
You will need to use fragments for each Tab.
Your MainActivity- Class:
#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);
}
}
Your Fragment class:
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
}
That should do. The same/similiar code also for TabTwo ofc.
I think i should edit this code :
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;
}
}
and the XML file and replacte textview with a menu ?
<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>