FragmentActivity to Fragment - java

I haven't found any question like this on here so I wanted to ask. Please keep in mind that I'm new to Fragments & FragmentActivity (not Android) and I don't really know how to work with them quite yet but I'm learning. My question is I want to know how to change from a FragmentActivity to a Fragment so I can incorporate it into my app seamlessly without any errors. The code I want to rid errors of is below
public class Work extends Fragment implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Tattoos", "Piercings", "Social Networks" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.our_work);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
I've tried 3 different ways of doing this by rearranging the code but nothing works. Please help me with this!
EDIT I've tried it this way now
public class Work extends Fragment implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Tattoos", "Piercings", "Social Networks" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.our_work, container, false);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
return rootView;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}

first of all;
a Fragment must be inside a FragmentActivity, that's the first rule,
a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout
here is an example:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_layout, container, false);
return mView;
}
and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);
for the FragmentActivity part:
the xml part "must" have a FrameLayout in order to inflate a fragment in it
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

Related

OnClick Fragment to Fragment switch results in Blank Screen

When switching from one fragment to another fragment (within the second tab of my application), my second fragment is blank. I have tried the solutions linked here, but none seem to work:
Transaction of fragments in android results in blank screen
Android: Getting white screen with fragment transaction
MainActivity:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter, and add pages.
mViewPager = (ViewPager) findViewById(R.id.container);
mSectionsPagerAdapter.addPage(new Received());
mSectionsPagerAdapter.addPage(new Send());
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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_alert_partners, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getArguments().getInt(ARG_SECTION_NUMBER)==1) {
View rootView = inflater.inflate(R.layout.fragment_received, container, false);
return rootView;
}
else if(getArguments().getInt(ARG_SECTION_NUMBER)==2) {
View rootView = inflater.inflate(R.layout.fragment_send, container, false);
return rootView;
}
else {//main empty fragment in case of error. Never used in normal behaviour.
View rootView = inflater.inflate(R.layout.fragment_alert_partners, container, false);
return rootView;
}
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
//Create an Array list that will hold the pages.
ArrayList<Fragment> pages = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
return pages.get(position);
}
//Add a page
public void addPage(Fragment f) {
pages.add(f);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Received";
case 1:
return "Send";
}
return null;
}
}
}
SendFragment:
public class Send extends Fragment {
private OnFragmentInteractionListener mListener;
private TextView text1;
public Send() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_send, container, false);
//Need getView() for fragment since setContentView must be set first but is not possible in fragment.
text1 = (TextView)v.findViewById(R.id.textview1);
text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Send2 send2 = new Send2();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.hide(Send.this);
fragmentTransaction.add(android.R.id.content, send2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return v;
}
public interface OnFragmentInteractionListener {
}
}
Send2Fragment:
public class Send2 extends Fragment {
private OnFragmentInteractionListener mListener;
public Send2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_send2, container, false);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
}
}
Had to add a framelayout at the end of the layout code for the fragment I was replacing:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/send1frameLayoutId">
</FrameLayout>
Then used this code to switch to a fragment in the same tab of the previous fragment:
Fragment send2 = new Send2();
FragmentManager fragmentManager = getChildFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.send1frameLayoutId, send2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

Java Android remove name of Application

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

How to change xml layout of second tab according to the selection of spinner item in first tab android

I have added 3 tabs as following.There is a spinner(drop down list) in “IntroductionFragment”.i want to change the layout of “RequirementFragment” programmatically according to the selection of spinner item in “IntroductionFragment”.Please help me
HomeLoanTabMainActivity.java
public class HomeLoanTabMainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Introduction", "Requirement", "Best offer" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_main_activity);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
TabsPagerAdapter.java
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new IntroductionFragment();
case 1:
return new RequirementFragment();
case 2:
return new BestOfferFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
IntroductionFragment.java
public class IntroductionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(
R.layout.introductionform_layout, container, false);
return rootView;
}
}
RequirementFragment.java
public class RequirementFragment extends Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(
R.layout.requirementFragment_layout, container, false);
return rootView;
}
}
Just give this a try
Inside your RequirementFragment.java add the onResume method as below:
public class RequirementFragment extends Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(
R.layout.requirementFragment_layout, container, false);
return rootView;
}
#Override
public void onResume() {
super.onResume();
Toast.makeText(getActivity(), "Just check if you see this every time", Toast.LENGTH_SHORT).show();
}
}
Now run your code. In case you get the Toast every time you go back and forth then we can proceed.

Replace a fragment above another fragment when dialog is clicked (viewpager)

I am trying to open a fragment, when a dialog is clicked inside another fragment. I am using ActionBarSherlock with Tab. My fragment is attached in the view pager. I have almost done the job. But I can't replace a new fragment inside a view pager. I got an error. I read the thread here. The solution isn't clear.
Error:
10-18 21:34:40.379: E/AndroidRuntime(19618): FATAL EXCEPTION: main
10-18 21:34:40.379: E/AndroidRuntime(19618):
java.lang.IllegalArgumentException: No view found for id 0x7f040032
(com.example.actionbartestwithsherlock:id/pager) for fragment
AllContactsFragment{41fd4ba0 #0 id=0x7f040032} 10-18 21:34:40.379:
E/AndroidRuntime(19618): at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:903)
I have three fragment associates with pager named FragmentTab1,FragmentTab2 & FragmentTab3.
My MainActivity & FragmentAdapter looks like below:
public class MainActivity extends SherlockFragmentActivity {
ActionBar.Tab Tab1, Tab2, Tab3, Tab4;
private Context context = this;
// view pager
// Declare Variables
ActionBar actionBar;
ViewPager mPager;
Tab tab;
FragmentAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set application in portrait mode
ActivityHelper.initialize(this);
actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Locate ViewPager in activity_main.xml
mPager = (ViewPager) findViewById(R.id.pager);
// add an adapter to pager
mPager.setAdapter(new FragmentAdapter(getSupportFragmentManager(),
mPager, actionBar));
addActionBarTabs();
}
private void addActionBarTabs() {
String[] tabs = { "Tab 1", "Tab 2", "Tab 3" };
for (String tabTitle : tabs) {
ActionBar.Tab tab = actionBar.newTab().setText(tabTitle)
.setTabListener(tabListener);
actionBar.addTab(tab);
}
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
private ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
class FragmentAdapter extends FragmentPagerAdapter implements
ViewPager.OnPageChangeListener {
private ViewPager mViewPager;
final int TOTAL_PAGES = 3;
public FragmentAdapter(FragmentManager fm, ViewPager pager,
ActionBar actionBar) {
super(fm);
this.mViewPager = pager;
this.mViewPager.setOnPageChangeListener(this);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragmentTab1.newInstance();
case 1:
return FragmentTab2.newInstance();
case 2:
return FragmentTab3.newInstance();
default:
throw new IllegalArgumentException(
"The item position should be less or equal to:"
+ TOTAL_PAGES);
}
}
#Override
public int getCount() {
return TOTAL_PAGES;
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
}
}
Now, Inside my first tab FragmentTab1, I open a customized dialog when a button clicks. I want to replace new fragment AllContactsFragment in FragmentTab1 when the dialog options are selected.
FragmentTab1 fragment class:
public class FragmentTab1 extends SherlockFragment implements OnClickListener {
Button btnTest;
ViewPager pager;
LinearLayout layoutBlockNumbers;
LinearLayout layoutContact, layoutCallLog, layoutSMSLog, layoutManually;
Context context;
CustomizedDialog dialog;
private static final int CONTACT_PICKER_RESULT = 1001;
private static final String DEBUG_TAG = "Contact List";
private static final double RESULT_OK = -1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab1, container,
false);
layoutBlockNumbers = (LinearLayout) rootView
.findViewById(R.id.layoutAddBlockNumbers);
layoutBlockNumbers.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
if (v == layoutCallLog) {
dialog.dismiss();
// want to replace new fragment at position 0 in pager
// problem is here ??? how to open new fragmnet
Fragment allContactsFragment = AllContactsFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.pager, allContactsFragment).commit();
}
if (v == layoutBlockNumbers) {
// open a dialog
showDialog();
} else if (v == layoutContact) {
openContactList();
dialog.dismiss();
} else if (v == layoutSMSLog) {
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
// open a dialog
private void showDialog() {
dialog = new CustomizedDialog(getActivity());
dialog.setContentView(R.layout.dialog_add_number_type);
dialog.setTitle("Add Black List Number");
//initialize all linear layouts in dialog
layoutCallLog = (LinearLayout) dialog.findViewById(R.id.layoutCallLog);
layoutContact = (LinearLayout) dialog.findViewById(R.id.layoutContact);
layoutSMSLog = (LinearLayout) dialog.findViewById(R.id.layoutSMSLog);
layoutManually = (LinearLayout) dialog
.findViewById(R.id.layoutManually);
// add listener to several linear layout
layoutContact.setOnClickListener(this);
layoutCallLog.setOnClickListener(this);
layoutSMSLog.setOnClickListener(this);
layoutManually.setOnClickListener(this);
dialog.show();
}
public static Fragment newInstance() {
Fragment f = new FragmentTab1();
return f;
}
}
activity_main.xml looks like below :
<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.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
Can anybody can help me to solve this issue? Sorry for the massive code.
I'm not sure you can do things the way you want to. A ViewPager is not set up the same way a normal container/fragment set up would be. In a ViewPager you're not using fragment transactions to add fragments but rather an adapter that loads instances of fragments from a backing list.
Replacing the fragment would then work as follows:
(1) Create an instance of the fragment you want to add
(2) Add that fragment to the list that is backing your PagerAdapter
(3) Display the new fragment
(4) Remove the old one
The problem with implementing this in your current project is the set up of your adapter. Currently you are using a switch statment that can only return a fixed number of fragments. Your adapter should be set up something like this.
class MyPageAdapter extends FragmentPagerAdapter{
private List<Fragment> fragments
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
Then you can just add a method to your adapter class to add or remove new fragments. If you know the index of the fragment you want to replace accomplishing this should be pretty easy. All you have to do is create a new instance of the contacts fragment, add it to your array or list. This Post explains how a ViewPager handles the adding/removing of new content and how to ensure your new fragment is displayed.
After I read this post I solved the answer.
I just add an ID android:id="#+id/fragmentTabLayout1 to top layout of my fragmenttab1.xml . Then call
new fragment as usual:
Fragment allContactsFragment = AllContactsFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
transaction.addToBackStack(null);
// use this id to replace new fragment
transaction.replace(R.id.fragmentTabLayout1, allContactsFragment).commit();

submenu in ActionBar Tabs android code

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>

Categories