In order to create a Navigation Drawer, and because it seemed confusing, I used Eclipse's automatically created template. However, this template creates code so that it displays the content of a String array adapter, and at the selection of an item a Fragment is instantiated in the attached Activity like this:
#Override
public void onNavigationDrawerItemSelected(int position)
{
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = null;
switch (position)
{
case 0:
fragment = new FragmentType0();
break;
case 1:
fragment = new FragmentType1();
break;
case 2:
fragment = new FragmentType2();
break;
default:
Log.w(this.getClass().getSimpleName(), "Reached Default in onNavigationDrawerItemSelected!");
break;
}
if (fragment != null)
{
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.container, fragment);
ft.addToBackStack(null);
ft.commit();
mTitle = getString(((GetActionBarTitle) fragment).getActionBarTitleId());
restoreActionBar();
}
}
Because the generated template is the following:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
mDrawerListView = (ListView) inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
selectItem(position);
}
});
String[] drawerTitles = new String[] { getString(R.string.drawer_string_0), getString(R.string.drawer_string_1), getString(R.string.drawer_string_2)};
mDrawerListView.setAdapter(new ArrayAdapter<String> (getActionBar().getThemedContext(), android.R.layout.simple_list_item_1,
android.R.id.text1, drawerTitles));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
So as you can see, the titles are given in the navigation drawer, displayed and specified as a String, and when you select an item, the callback is called on the Activity, at which based on position of selected item, the 'proper' Fragment is instantiated based on an if-else structure. This seems like a fairly fragile solution, but I can't seem to figure out how to make it better.
My hunch is something like using a FragmentStatePagerAdapter, but I'm at a loss, as I've never used one before, especially not in this particular context (I'm REALLY new to the navigation drawer, and I don't know how I would integrate it with the navigation drawer, so that it displays strings that correspond to each Fragment). Can anyone please provide advice on what to do here? It works, but it doesn't seem like the "proper" solution.
I'd reccomend that you stay away from the auto-generated code. A lot of the time, it isn't at all what you want.
I recommend you take a look at this tutorial. It explains the basics of the navigation drawer pretty well.
Related
UPDATE: I have found the header isn't the only thing affected, but listeners and other elements in the fragment aren't being initialized. (Such as FAB's). The only things that function correctly is anything built inside the adapter (i.e. the ListView rows)
The Problem: Open Nav Drawer, click on a list item that opens up a new Fragment in the same Activity. Open the Nav Drawer again, click the same item that should simply replace the existing Fragment and while the Fragment does open, all of the elements that are set programmatically in Java (text, colors, listeners) are not changed/added to the Fragment. The view is simply the default xml layout. I have confirmed with Log.d that the code that sets these things is being ran. (If you open a different Fragment and then go back to the original one, everything works fine)
The Confirmed Cause: When changing this:
compile "com.android.support:appcompat-v7:25.0.1"
compile 'com.android.support:design:25.0.1'
to
compile "com.android.support:appcompat-v7:25.1.0"
compile 'com.android.support:design:25.1.0'
(if only one of these libraries is changed, it doesn't matter which one, the problem still occurs)
I have confirmed changing these two libraries is the problem (also confirmed this problem in a second app -- and changing only this code, has the exact same result)
My questions is, why is this happening and how can it be fixed?
The Code and more detailed description from original question:
FragmentTransaction tItems = fm.beginTransaction();
ListFragment mFrag = new PlannerFragment();
tItems.replace(R.id.main_frag, mFrag, TAG_CALC_FRAGMENT);
tItems.commit();
There are about 4 options in my drawer that all open this Fragment, but before each one, I set a global variable like this:
MyApp.PlanType = "highbal";
MyApp.PlanType = "lowbal";
etc.
Based on the PlanType value (above), that Fragment is loaded with different data (but, in the exact same xml layouts). It is simply a ListView with a header.
This Fragment, (PlannerFragment) loads fine the first time.
When I click on another item (a different PlanType) that goes to the same Fragment (same code above executed): The ListView loads fine in the actual list. But in the header in the list, none of the setText() values set the new data properly. It uses the default values from my xml layout.
Now, if I load a different Fragment in between, everything works great. It's only when I either add or replace (I've tried both) the same Fragment on top of the old one does this happen.
Here is header code at top of PlannerFragment
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Setup listview
lv = getListView();
LayoutInflater inflaterHeader = getActivity().getLayoutInflater();
ViewGroup header = (ViewGroup) inflaterHeader.inflate(R.layout.planner_listview_header, lv, false);
lv.addHeaderView(header, null, false);
// Load Data then Set Textviews, e.g.:
TextView title = (TextView) getActivity().findViewById(R.id.tvPlannerTitle);
dateOutput = (TextView) getActivity().findViewById(R.id.tvDebtOutDate);
If I add to that code, dateOutput.setText("test"); it does not happen. I can do a Log.dand my data registers, so this code is being read, but the UI is not set.
I've even tried removing the Fragment first like this with a check:
Fragment fragment = fm.findFragmentByTag(TAG_CALC_FRAGMENT);
if(fragment != null)
fm.beginTransaction().remove(fragment).commit();
This has no effect.
Again, this ONLY happened when I changed the libraries above. Is this a bug with the library or does it now respond differently?
There is many changes and issues with Fragments on appcompat 25.1.0. The first one seems related to your issue but the two next should be read as it may be important.
FragmentTransaction replace behaviour
Replace not working properly in appCompat 25.1.0
Current status (Jan 4 2017): bug assigned
Issue link
Fragment lifecycle change on 25.1.0
onStart on new Fragment is called before onStop on previous one
Current Status : works as expected. For me it could be a breaking change from app compat 25.0.x
Issue link
There is also an issue with the resume event called two times in fragment, see here.
TLDR. Maybe the best temporary solution is to not use 25.1.0 until a new version is out.
you can add list_view_header.xml in navigationDrawer() method and change the position of selected item like selectItem(position - 1).
private void navigationDrawer() {
mTitle = mDrawerTitle = getTitle();
// mNavigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
LayoutInflater inflater = getLayoutInflater();
View listHeaderView = inflater.inflate(R.layout.list_view_header, null, false);
mDrawerList.addHeaderView(listHeaderView, null, false);
setupToolbar();
DataModel[] drawerItem = new DataModel[6];
drawerItem[0] = new DataModel(R.drawable.dashboard_icon, "Dashboard");
drawerItem[1] = new DataModel(R.drawable.cal_icon, "Calender");
drawerItem[2] = new DataModel(R.drawable.classes, "Classes");
drawerItem[3] = new DataModel(R.drawable.message_icon_hdpi, "Message Center");
drawerItem[4] = new DataModel(R.drawable.profile, "Profile & Setting");
drawerItem[5] = new DataModel(R.drawable.bulletin_icon, "Bulletin Board");
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.list_view_item_row, drawerItem);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerListener(mDrawerToggle);
setupDrawerToggle();
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position - 1);
}
}
private void selectItem(int i) {
Fragment fragment = null;
switch (i) {
case 0:
fragment = new Fragment_DashBoard();
// toolbar.setTitle("Dashboard");
Titletv.setText("Dashboard");
break;
case 1:
fragment = new Fragment_Calender();
// toolbar.setTitle("Calender");
Titletv.setText("Calender");
break;
case 2:
fragment = new Fragment_Classes();
// toolbar.setTitle("Classes");
Titletv.setText("Classes");
break;
case 3:
fragment = new Fragment_MessageCenter();
// toolbar.setTitle("Message");
Titletv.setText("Messages");
break;
case 4:
fragment = new Fragment_ProfileSetting();
// toolbar.setTitle("Profile");
Titletv.setText("Profile");
break;
case 5:
fragment = new Fragment_BulletinBoard();
//toolbar.setTitle("Bulletin Board");
Titletv.setText("Bulletin Board");
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction trans = fragmentManager.beginTransaction();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit();
mDrawerList.setItemChecked(i, true);
mDrawerList.getItemAtPosition(i);
// setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
Answered: I had a searchview in Fragment A that still had focus behind Fragment B, so the first backpress was clearing that focus, letting the second backpress do what I thought it should. Thank you for your help, I apologize the information I posted originally wasn't sufficient in helping me find a solution to my problem.
Problem
I'm running into an issue where when I add and commit a new fragment, it requires two back button presses to return to the previous view.
Note: this only occurs on the first item you select, once you succesfully back out to the fragment containing the listview and select the object again or a new object it only requires you press the back button once.
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) {
final Obj item = (obj) adapter.getItemAtPosition(position);
Bundle b = new Bundle();
b.putParcelable("obj", item);
Fragment fragment = new ObjFragment();
fragment.setArguments(b);
getFragmentManager().beginTransaction().add(android.R.id.content, fragment).addToBackStack(null).commit();
}
});
I have a listview of objects when I select an object a new fragment is started, nothing fancy is done inside the fragment, just populates some information text boxes etc..
I've checked to see if it was possibly starting two fragments so I might need to back out twice to close and return to the previous fragment, but that is not the case.
I've also tried to override the onBackPressed method in my activity, and it is only called after the second back button is pressed, I am unsure what this means. Any suggestions are welcome, it's probably something really simple that I'm just overlooking.
This is inside my MainActivity, it contains 3 fragments in the form of tabs, I'm dealing with tab3 at the moment, which contains the above listener for the listview.
private ViewPager mViewPager;
private SlidingTabLayout tabs;
private CharSequence Titles[] = {"Recent", "Library", "All"};
private int Numbtabs = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numbtabs);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mViewPagerAdapter);
mViewPager.setOffscreenPageLimit(3);
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(mViewPager);
}
//trying to solve double back button to exit objfragment
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0){
getSupportFragmentManager().popBackStack();
}
else{
super.onBackPressed();
}
}
Answered: I had a searchview in Fragment A that still had focus behind Fragment B, so the first backpress was clearing that focus, letting the second backpress do what I thought it should. Thank you for your help, I apologize the information I posted originally wasn't sufficient in helping me find a solution to my problem.
you can do something like this in your code
//Click of the Item
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) {
final Obj item = (obj) adapter.getItemAtPosition(position);
Bundle b = new Bundle();
b.putParcelable("obj", item);
Fragment fragment = new ObjFragment();
fragment.setArguments(b);
getFragmentManager().beginTransaction().add(android.R.id.content, fragment).addToBackStack("ObjFragment").commit();
}
});
//Backpress code
FragmentManager fragmentManager = getFragmentManager();
try {
fragmentManager.popBackStack();
} catch (Exception e) {
e.printStackTrace();
}
Answered: I had a searchview in Fragment A that still had focus behind Fragment B, so the first backpress was clearing that focus, letting the second backpress do what I thought it should. Thank you for your help, I apologize the information I posted originally wasn't sufficient in helping me find a solution to my problem.
I am attempted to create an application in Android studio that has a navigation drawer.
I am using Android Studio (beta)0.8.14. In this version, there is a navigation drawer activity. I been able to set the labels for my navigation drawer menu using this piece of code and the corresponding values in my strings file
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.login);
break;
case 2:
mTitle = getString(R.string.sign_up);
break;
case 3:
mTitle = getString(R.string.view_map);
break;
case 4:
mTitle = getString(R.string.about);
break;
case 5:
mTitle = getString(R.string.version);
}
}
It looks really nice, but I can't figure out how to add onClickListeners for each of the items.
I've also added this in my NavigationDrawerFragment.java (which was automatically created by Android Studio):
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.login),
getString(R.string.sign_up),
getString(R.string.view_map),
getString(R.string.about),
getString(R.string.version),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
I would like to launch a different activity for each of the list items but I can't understand how and unfortunately I can't seem to find a tutorial that uses Android Studio's built-in navigation drawer activity.
Also, is it possible to have this navigation drawer available on all of my activities? Do I need to create a new navigation drawer fragment every time I create a new activity?
Thanks in advance!
The idea of having a navigation drawer is to use fragment. It wouldn't be very efficient to launch a new activity whenever you click an item in your navigation drawer.
In your selectItem(position) method you could execute some code for creating a new fragment for list item in your navigation drawer. Each navigation item should be a different fragment then just use a fragment transaction to add it to the container view of the main activity.
As a simple example of what the method may look like:
private void selectItem(int position) {
FragmentManager fragmentManager = getFragmentManager();
switch(position) {
//fragment for position 0
case 0:
fragmentManager.beginTransaction()
.replace(R.id.container, new Fragment0())
.commit();
break;
//fragment for postion 1
case 1:
fragmentManager.beginTransaction()
.replace(R.id.container, new Fragment1())
.commit();
break;
//fragment for position 2
case 2:
fragmentManager.beginTransaction()
.replace(R.id.container, new Fragment2())
.commit();
break;
default:
break;
}
}
This may not be exactly what you want but it is an option for what you're trying to accomplish.
As a note in order for onSectionAttached() to work, all your framents will have to call that to pass their title to the main activity.
See this link for more info.
In order to put onclicklisteners on your navigation drawer, just put an intent below the line of code where you are changing the title bar i.e. in the switch case block
e.g.
case 1:
mTitle = getString(R.string.login);
Intent transfer = new Intent(HomeFragment.this,NextActivity.class);
startActivity(transfer);
This will do it for you.
I use the Sliding Menu library in my app.
The sliding menu is a fragment.
The blue part is the sliding menu when opened.
The red part is static, it doesn't change, it's the main activity btw.
The yellow part is the fragment that change when the user clicks on an item of the sliding menu.
Here's what's wrong when I implement it :
In the sliding menu fragment, I listen for the OnItemClick event, and I create a new fragment depending on the position of the item clicked.
After that, I replace the yellow frame id, with the fragment.
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment frag = null;
switch (arg2) {
case 1:
frag = new ExpFragment();
break;
case 2:
frag = new FormFragment();
break;
case 3:
frag = new CompFragment();
break;
default:
frag = new ContactFragment();
break;
}
transaction.replace(R.id.fragment, frag);
transaction.commit();
}
Looks good huh? Well, no. Here's the logcat exception I got.
06-13 09:28:29.739: E/AndroidRuntime(15422): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
So, if anyone has a clue, or can tell me what to look at, that'd be awesome!
TL;DR : Have 2 fragments (bleu and yellow), the blue has to change the yellow. Gives me an exception.
Thanks,
EDIT: The layouts file:
The activity_main : https://gist.github.com/dommerq/5771887
One fragment item example : https://gist.github.com/dommerq/5771892
The answer was in my fragment java code.
I had :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(com.quentindommerc.flatme.R.layout.f_contact, container);
return v;
}
And I should have :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(com.quentindommerc.flatme.R.layout.f_contact, container, false);
return v;
}
So basically, in the inflate method, put "false" as third parameter.
Edit : Corrected spelling mistake.
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.