getSupportFragmentManager().findFragmentById() returns null - android

I am trying to implement fragment communication in android like the one in the android guide http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
but my application is crashing as the getSupportFragmentManager().findFragmentById() returns null. What is the issue with my implementation.
The code is given below:
The program is just to send an input text from one fragment to another fragment textView area through a button click from first fragmnet.I have an activity_main.xml and two fragment layout (two separate xml files rather than part of in activity_main.xml)
Frag1.java
public class Frag1 extends Fragment {
public Frag1(){
}
buttonClickListener buttonListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
buttonListener = (buttonClickListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnButtonPressListener");
}
}
View myFragmentView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.frag1, container, false);
//SetValue Button
Button setValueButton = (Button) myFragmentView.findViewById(R.id.setValueButton);
setValueButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
buttonListener.onButtonPressed("Message received");
}
});
return myFragmentView;
}
}
Frag2.java
public class Frag2 extends Fragment {
View myFragmentView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.frag2, container, false);
return myFragmentView;
}
void setMessage(String msg){
TextView txt=(TextView)myFragmentView.findViewById(R.id.textView1);
txt.setText(msg);
}
}
buttonClickListener.java
public interface buttonClickListener {
public void onButtonPressed(String msg);
}
MainActivity.java
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener, buttonClickListener {
SectionsPagerAdapter mSectionsPagerAdapter;
#Override
public void onButtonPressed(String msg) {
// TODO Auto-generated method stub
Frag2 fragmentObj=(Frag2) getSupportFragmentManager().findFragmentById(R.layout.frag2);
fragmentObj.setMessage(msg);
}
Please tell me where did I go wrong?
EDIT:
I am using fragment creation using the template generated by Android Plug-in eclipse IDE.
So the fragments are created using android.support.v4.app.Fragment
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch(position)
{
case 0:
return new Frag1();
case 1:
return new Frag2();
}
return fragment;
}
The codebase is kept here for reference
https://skydrive.live.com/redir?resid=D37E0F56FEC9B499!259

Try This it works for me How to put Google Maps V2 on a Fragment Using ViewPager
<fragment
android:id="#+id/map"
android:layout_width="wrap_content"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
GoogleMap mGoogleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();

You should have added the fragment Frag2 by calling
getSupportFragmentManager().beginTransaction().add(R.id.frag2_view, new Frag2(), "tag").commit();
at your MainActivity, where R.id.frag2_view is a layout defined in your main_layout.
To get that Fragment, you should then call
Frag2 obj = (Frag2)getSupportFragmentManager().findFragmentById(R.id.frag2_view);
passing the layout id you used to add the fragment in the main_layout.
Hope it helps.
EDIT:
Since you use a ViewPager, you should use R.id.pager as the ID.
I just tried with your example and it worked.
Frag2 fragmentObj=(Frag2) getSupportFragmentManager().findFragmentById(R.id.pager);
EDIT 2:
Despite it worked, I don't really think this is the correct way, since R.id.pager its from ViewPager and you can't find, let's say, frag4 or frag5.
Ignore my answer please. I'm not sure how to do that with ViewPager, sorry.

I was having a similar problem and here is the solution.
To get the reference to the proper fragment inside the viewpager just call:
getSupportFragmentManager().findFragmentByTag(tag);
The tag param you can build it using the following syntax: "android:switcher:pager_id:index", where pager_id is the id of the ViewPager in the XML layout and the index is the position of your fragment inside the ViewPager starting by zero. See the original response here: https://stackoverflow.com/a/7393477/2423274

Found the right solution for this question.
Hope more people see this.
Frag2 fragmentObj=(Frag2) mSectionsPagerAdapter.getItem(2);
You should use your Adapter (where you populate your fragments) as a source for get the Fragment reference.

I used this to get a child fragment from a fragment adapter...
Fragment parent = MainActivity.this.getSupportFragmentManager().findFragmentById(R.id.main_container);
if (parent instanceof PagerFragment) {
// do something with parent
Fragment child = ((PagerFragment) f).adapter.getItem(childPosition);
}

Related

Connecting Fragments using ImageButton in Android

I'm new Android programming. Earlier I was working with activities, where i could implement onClick on an ImageButton and go to a different activity.
Now I need to do the same but using Fragments. I have a prototype with a menu that always appear on screen and can show different activities to the user. The different lactivities would be inside this container.
Now I want to place an ImageButton inside a fragment and make that the screen shows the next fragment. But I'm confused how to do it.
I have the following components:
Activity_main(java)+activity_main.xml (with menu)
Fragment1(java)+fragment1.xml(working normal)
Inside this layout I have an ImageButton and want to show Fragment2
Fragment2(java)+fragment2.xml
How should look Fragment1 to can call Fragment2?
I will be glad if the answer could be the clearest possible because I'm new on it, and maybe I could forgot an obvious step. Thanks
Simply make a method in your activity which will always change/replace fragment when you invoke it. something like
public void updateFragment(Fragment fragment){
//add fragment replacing code here
}
in your fragment, invoke it some thing like this
((YourActivity)getActivity()).updateFragment(new YourFragment());
since, it is just an idea which works fine but still you can improve the logic.
Actually, going from one fragment to another is almost similar to going from one activity to another. There are just a few extra lines of code.
First, add a new Java class named SingleFragmentActivity which would contain the following code-
public abstract class SingleFragmentActivity extends AppCompatActivity
{
protected abstract Fragment createFragment();
#LayoutRes
protected int getLayoutResId()
{
return R.layout.activity_fragment;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(getLayoutResId());
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null)
{
fragment = createFragment();
fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
}
}
}
Make your activities in the following format-
public class SomeActivity extends SingleFragmentActivity
{
#Override
protected Fragment createFragment()
{
return SomeFragment.newInstance();
}
}
And your fragments like this-
public class SomeFragment extends Fragment
{
public static SomeFragment newInstance()
{
return new SomeFragment();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_some, container, false);
return v;
}
}
After this everything has the same code as you have for activities except for one small detail which is your onCreateView(LayoutInflater, ViewGroup, Bundle) class. This is how you would write it-
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_some, container, false);
mTextView = (TextView)v.findViewById(R.id.some_text);
mButton = (Button)v.findViewById(R.id.some_button);
mTextView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
check();
}
});
return v;
}
And that is it!
Hi i hope you are already aware about the fragments and their uses but still here is a brief. They are child to an activity and an activity can have more than one fragment so you can update your layout without changing activity just by changing fragments.
You can found more on fragment here : https://developer.android.com/training/basics/fragments/index.html
Back to the original problem, supposed you are in MainActivity.java and you want to load fragment in it, so you do this to load fragment first time.
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, new Fragment1);
transaction.addToBackStack(null);
transaction.commit();
You will need this method to change fragment from another fragment, so add this in your MainActivity
public void changeFragment(Fragment fragment){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, new Fragment1);
transaction.addToBackStack(null);
transaction.commit();
}
Now from a button click in this fragment
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).changeFragment(new Fragment2);
}
});
Hope it will help!

make Simple Fragment always get InstantiationException

hello guys i just try to make a simple fragment start up using support library v4 here...
this is my main activity
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment testFragment = manager.findFragmentById(R.id.listTestFragment);
transaction.show(testFragment);
transaction.commit();
}
}
and my activity_main.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.drikvy.testfragmentgame.ListTestFragment"
android:id="#+id/listTestFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
and my ListTestFragment.java
public class ListTestFragment extends Fragment {
String[] data = {"aaaa", "bbbb", "cccc", "dddd"};
MainActivity activity;
public ListTestFragment(MainActivity activity) {
this.activity = activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_lores_list, null, false);
ListView lvLores = (ListView) view.findViewById(R.id.lv_saved_lores);
lvLores.setAdapter(new ArrayAdapter<String>(activity, android.R.id.text1, data));
return view;
}
}
sadly android runtime said that i havent empty constructor and that my fragment class is not public class etc
what's wrong?
UPDATE
Thanks to Sir Miro for pointing out the main problem in my code through his answer.
I just want to make clear some matters here:
first of all, i didnt know that by putting the fragment in the xml layout would require the fragment class to provide an empty constructor, that's why im always getting instantiate exception error in logcat
the reason behind why i didnt put an empty constructor in my fragment class is that because from my previous attempts for making fragments i had successfully show the fragments by using non-empty constructor and i usually add activity parameters inside it for context utilization within the fragment class. but i didnt noticed that none of these fragments was declared on my xml layout! and thats when the error start to popped up
so in conclusion we have to provide an empty constructor or no constructor at all if we have declared the fragments on our xml layout. but if we didnt declared them on our xml layout then we can deliberately add any kinds of constructor with any parameters we could possibly wanted within our fragment class!
You can't pass in your activity from the fragment constructor. Fragment has a method called onAttach which is called when the fragment is attached to an activity. You can set the activity variable from onAttach.
Try this as your Fragment code:
public class ListTestFragment extends Fragment {
String[] data = {"aaaa", "bbbb", "cccc", "dddd"};
MainActivity activity;
public ListTestFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_lores_list, null, false);
ListView lvLores = (ListView) view.findViewById(R.id.lv_saved_lores);
lvLores.setAdapter(new ArrayAdapter<String>(activity, android.R.id.text1, data));
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (MainActivity) activity;
}
#Override
public void onDetach() {
super.onDetach();
this.activity = null;
}
}
And also you won't need all that code in your activity. Android will initialize and show the fragment for you automatically.

Is it the correct way? : To change a view/layout of Fragment on click

What I ought to do is change the view/layout of Fragment without creating another class for fragment on click of a button.
For example I have an activity - ContactsActivity and I have a fragment - ContactsFragment.
The Standard way of using Fragments:
From ContactsActivity I call ContactsFragment by -
getFragmentManager().beginTransaction().replace(android.R.id.content, new ContactsFragment())
.commit();
Code for setting View in ContactsFragment class -
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.contacts_primary, container, false);
return rootView;
}
**Now comes how I do what I want to do ** (Change the view of fragment)
I change only the view of ContactsFragment by doing a bad kind of hack.
I change the onCreateView() shown above to this -
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
//Set the view to R.layout.contacts_primary
rootView = inflater.inflate(R.layout.contacts_primary, container, false);
//Set the view to R.layout.contacts_secondary
if(getActivity().getIntent()!=null && getActivity().getIntent().getBooleanExtra("s", false)) {
rootView = inflater.inflate(R.layout.contacts_secondary, container, false);
Log.e(tag,getActivity().getIntent().getExtras().toString());
return rootView;
}
//This is the onClickListener which again calls the ContactsActivity class,
//this time with an Intent which I used above to change the view from
//R.layout.contacts_primary to R.layout.contacts_secondary
Button button = (Button)rootView.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), ContactsActivity.class).putExtra("s",true));
}
});
Now everything works as I want and flawlessly.
But I have a very strong feeling that either all of it is wrong and Fragments aren't supposed to work this way or I am using a hectic hack to achieve what can be done by few lines of code.
So please let me know what is it? And if there is a standard way of doing what I am trying to do.
For me passing additional argument on which base fragment decides wich layout to use seems totally ok. But there is cleaner way of doing what you want to achieve without starting another activity.
First of all pass argument to fragment by making standard static new instance method in fragment (we cannot pass this argument in constructor as android always recreates fragments using empty constructor). Something like this:
public static ContactsFragment newInstance(boolan firstView) {
ContactsFragment fragment = new ContactsFragment();
Bundle args = new Bundle();
args.putBoolean("yourArg", firstView);
fragment.setArguments(args);
return fragment;
}
Every time you have to initiate your fragment do this with this method.
Then declare interface in your fragment to communicate with your activity. Like this
public interface NewViewListener {
public void showNewView(boolen firstView);
}
Than make your activity implement it so your activity han a method where it can place new fragment in container view. In your fragments onAttach and onDetach methodsmake sure your activity implements this interface and hold reference to your activity in private NewViewListener field in your fragment. Like this:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (NewViewListener ) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement NewViewListener ");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
Then in on button click method call showNewView method on your activity with whatever argument you want indicating which view you want in new fragment instance. And in your activity method showNewVew fragment in the container. Like this:
#Override
public void showNewView(boolean firstView) {
getFragmentManager().beginTransaction().replace(android.R.id.content, ContactsFragment.newInstance(firstView)
.commit();
}
In your fragments onCreateView you may get passed arguments and decide which view you want to use.

android - add Fragment in containerViewId to Fragment in ViewPager

I'm faced with following problem:
MainActivity is mainly a ViewPager where I can slide through cards (Fragment). This cards have a placeholder ViewGroup where another content (Fragment) is placed in during runtime. The problem is that the content is placed only in one card.
MainActivity
public class MainActivity extend FragmentActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// ...
// init ViewPager
getViewPager().setAdapter(new CardSelectionAdapter(getSupportFragmentManager()));
}
// ...
private class CardSelectionAdapter extends FragmentPagerAdapter {
// ...
public Fragment getItem(int position) {
return new CardFragment(someData);
}
}
}
CardFragment
public class CardFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.card, container, false);
rootView.findViewById(R.id.actionSheet).setVisibility(View.GONE);
return rootView;
}
public void populate() {
// ...
Fragment f;
switch (type) {
case TYPE_A: f = new ActionsAFragment(); break;
case TYPE_B: f = new ActionsBFragment(); break;
default: f = null;
}
if (f != null) {
// Here should be the main problem when adding Fragment to container/placeholder
getFragmentManager().beginTransaction().add(R.id.actionSheet, f).commit();
getView().findViewById(R.id.actionSheet).setVisibility(View.VISIBLE);
}
}
}
I think because all cards belong to MainActivity, FragmentTransaction can only add to one ViewGroup with id R.id.actionSheet.
Is there another way how I can add content to layout with same ids?
I don't see where you are calling populate. You should change populate to accept the parent view (instead of adding the fragment to R.id.actionsheet every time) and call it from onCreateView and pass it the view you just created. That way you don't have a problem with multiple views inside actionSheet with the same ID. However there is so much code missing I can't be exactly sure what to do here.
By the way, when you are dealing with nested fragments - inside of populate, you should use getChildFragmentManager() instead of getFragmentManager().

Dynamic UI with sliding menu and actionbarsherlock

Trying to achieve a dynamic UI with facebook like sliding menu and actionbarsherlock
.First i have look into android documentation which introduce fragment to handle dynamic button. But with no luck and a week time , i still can't get it to work anyhow , i guess is my misunderstand on android concept.The slidingbar and actionbarsherlock work without any problem.
I have a HomeScreen.java which contain all my menu and presetation stage
and so far i have created a pagerAdapter1.java that extends FragmentPagerAdapter
, and three example fragment class that handle my work which is task1.java,task2.java
,task3.java simple enough
here is part of my code
HomeScreen.java
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;
public class HomeScreen extends SlidingFragmentActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
setBehindContentView(R.layout.menu_frame);
}
PagerAdapter1.java
public class PagerAdapter1 extends FragmentPagerAdapter {
private List<Fragment> fragments;
public PagerAdapter1(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
public Fragment getItem(int position) {
return this.fragments.get(position);
}
public int getCount() {
return this.fragments.size();
}
}
and three task1.java,2,3
import android.support.v4.app.Fragment;
public class Tab1Fragment extends Fragment{
onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
return (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
}
I think its better to explain my problem with picture
A homescreen which is a presetation stage , whenever user click on menu , this page will change to the page he want
and this is my menu
My problem is how do i include this 3 fragment into my homescreen ? i have tried so many tutorial but it doesn't work in my situation.Most tutorial are creating fragment with code, i just want to include my 3 task into it
I´ll try to explain this sample code and you use for your need.
This is the ListFragment of your BehindContent (SlidingMenu):
public class ColorMenuFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] colors = getResources().getStringArray(R.array.color_names);
ArrayAdapter<String> colorAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, colors);
setListAdapter(colorAdapter);
//This array is only to fill SlidingMenu with a Simple String Color.
//I used MergeAdapter from Commonsware to create a very nice SlidingMenu.
}
#Override
public void onListItemClick(ListView lv, View v, int position, long id) {
//This switch case is a listener to select wish item user have been selected, so it Call
//ColorFragment, you can change to Task1Fragment, Task2Fragment, Task3Fragment.
Fragment newContent = null;
switch (position) {
case 0:
newContent = new ColorFragment(R.color.red);
break;
case 1:
newContent = new ColorFragment(R.color.green);
break;
case 2:
newContent = new ColorFragment(R.color.blue);
break;
case 3:
newContent = new ColorFragment(android.R.color.white);
break;
case 4:
newContent = new ColorFragment(android.R.color.black);
break;
}
if (newContent != null)
switchFragment(newContent);
}
// the meat of switching the above fragment
private void switchFragment(Fragment fragment) {
if (getActivity() == null)
return;
if (getActivity() instanceof FragmentChangeActivity) {
FragmentChangeActivity fca = (FragmentChangeActivity) getActivity();
fca.switchContent(fragment);
} else if (getActivity() instanceof ResponsiveUIActivity) {
ResponsiveUIActivity ra = (ResponsiveUIActivity) getActivity();
ra.switchContent(fragment);
}
}
}
Here is your BaseActivity Class:
It dont have swipe, as I could understand, you don't need this.
public class FragmentChangeActivity extends BaseActivity {
private Fragment mContent;
public FragmentChangeActivity() {
super(R.string.changing_fragments);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the Above View
if (savedInstanceState != null)
mContent = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
if (mContent == null)
mContent = new ColorFragment(R.color.red);
// set the Above View
//This will be the first AboveView
setContentView(R.layout.content_frame);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, mContent)
.commit();
// set the Behind View
//This is the SlidingMenu
setBehindContentView(R.layout.menu_frame);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.menu_frame, new ColorMenuFragment())
.commit();
// customize the SlidingMenu
//This is opcional
getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "mContent", mContent);
}
public void switchContent(Fragment fragment) {
// the meat of switching fragment
mContent = fragment;
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
getSlidingMenu().showContent();
}
}
Ok, So If you want to change the ColorFragment to anything else, do this:
First, choice the item that you want to use:
case 0:
newContent = new ColorFragment(R.color.red);
break;
to:
case 0:
newContent = new ArrayListFragment();
break;
I have made just a arraylist, it is just a simple example, you can do a lot of thing, then you can read about Fragment to learn how to do different things.
public class ArrayListFragment extends ListFragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, Listnames.TITLES));
//Listnames is a class with String[] TITLES;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList2", "Item clicked: " + id);
String item = (String) getListAdapter().getItem(position);
Toast.makeText(getActivity(), item, Toast.LENGTH_LONG).show();
}
}
Well, if you misunderstood something, just tell me.
My problem is how do i include this 3 fragment into my homescreen ?
It really depends on how do you want them to behave.
Do you want them to appear only one at a time without allowing swipeing between them? If yes then add/insert a container layout(for example a simple FrameLayout) in your Activity on which you'll add the Fragments. I didn't worked with the SlidingMenu library but it should have a callback called when you click one of the items in the menu. In that callback you'll attach the proper fragment to the container layout(the FrameLayout) I mention earlier.
Do you want to show only one Fragment but you want to allow the user to swipe between them? If yes use a ViewPager in the activity layout and in the callback triggered by the SlidingMenu library's menu selection set the current page of the ViewPager with the setCurrentItem() method.
If you want something different then this provide more details.
Most tutorial are creating fragment with code, i just want to include
my 3 task into it
This, I don't quite understand. If you want to "include" your task fragments directly in your xml layout, you can but you'll be limited on what you can do with them(not to mention that all the fragments will be on one single screen) and I would avoid it. If you want something else provide more details.
I don't think it will work like that with Fragments, I was looking for a solution as well and ended up adding the fragments by hand.
I'm working on something similar like this, but for me there was also the case of opening WebViews to designated URL's. So the "above" screen would always update on any click.
To control the behaviour of this I created a MenuItemResource object, which basically holds the properties, like the ID of the icon, the name of the menu item and the URL.
public class MenuItemResource {
private int aValue;
private int aUrl;
private int aIconIdle;
private int aIconActive;
public MenuItemResource(int value, int url, int iconIdle, int iconActive) {
aValue = value;
aUrl = url;
aIconIdle = iconIdle;
aIconActive = iconActive;
}
}
The behaviour is handled by an OnItemClickListener which checks with a switch which values are in the MenuItemResource that is being clicked. For the WebView it's quite straightforward:
newFragment = new WebViewFragment();
final Bundle arguments = new Bundle();
arguments.putString(Constants.KEY_URL, getString(item.getUrl()));
newFragment.setArguments(arguments);
startFragment(newFragment, false);
// boolean is used to add the fragment to the backstack
The startFragment method just uses the FragmentManager and FragmentTransaction to replace the current Fragment. This works the same for other MenuItemResources that do start regular fragments.
newFragment = new Task1Fragment();
startFragment(newFragment, false);
I don't refer to the fragments in the MenuItemResource (yet), but it works pretty well for URLs and WebViews. The fragments are started based on the value in the MenuItemResource
I'm not sure how you would refer to the fragments like you did in the comments (Task1.java, etc), since you don't start them with Intents like Activities. Also I'm not sure why you would want to do this dynamically for Fragments (I can imagine this case being dynamic for WebViews though) as they need to be compiled anyway, so that's why my menu items are added by hand.

Categories

Resources