I know this has been asked here but the answers were quite confusing. I have 3 items in my ListView. They are "Aluminium", "Gold" and "Zinc". Through each one of them, I want to start different activities and for that I have created the 3 activities which i named "Aluminium.java","Gold.java" and "Zinc.java"
I have used this ListView in a drawer layout for the navigation drawer. I implemented navigation drawers through the code given below which i got from a site.This code changes fragments and its not working properly. Instead of fragments, I want to switch activities.
I want to achieve 3 things:
Switch between activities through the listview in the navigation drawer.
To achieve point 1, I want to get the clicked list item and then use intents.
I want all the 3 activities to have this navigation drawer.
Sorry if its too dumb but I am a beginner. Please help me out with the code.
Java code
public class MainActivity extends FragmentActivity {
final String[] data ={"Aluminium","Gold","Zinc"};
final String[] fragments ={
"com.Chinmay.navigationdrawer.Gold",
"com.Chinmay.navigationdrawer.Aluminium",
"com.Chinmay.navigationdrawer.Zinc"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
final ListView navList = (ListView) findViewById(R.id.left_drawer);
navList.setAdapter(adapter);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView){
super.onDrawerClosed(drawerView);
android.support.v4.app.FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.content_frame, Fragment.instantiate(MainActivity.this, fragments[pos]));
tx.commit();
}
});
drawer.closeDrawer(navList);
android.support.v4.app.FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.content_frame,Fragment.instantiate(MainActivity.this, fragments[0]));
tx.commit();
}
});
}
}
Make a base activity class and put all your drawer code there, and extend this base class for your 3 activity, in that way, you'll have drawer for your all activities.
class Gold extends BaseActivity{
}
For the clicking part, you already set an item click listener, just make a switch case such as
switch (pos){
case 0:
Intent i = new Intent(this,Gold.java);
startActivity(i);
break;
}
// fill the rest
}
Related
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.
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.
The navigation drawer in my app is not closing. I am using activities instead of fragments. When i click on any item in the listview, it opens other activities as it should but when i go back, the drawer is still open. I have tried using DrawerLayout.closeDrawers(); but it did not work. How do I close the navigation drawer?
Here is my code:
Java
public class MainActivity extends FragmentActivity {
final String[] data ={"Aluminium","Gold","Zinc"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
final ListView navList = (ListView) findViewById(R.id.left_drawer);
navList.setAdapter(adapter);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
switch (pos){
case 0:
Intent i = new Intent(MainActivity.this,Aluminium.class);
startActivity(i);
break;
case 1:
Intent i2 = new Intent(MainActivity.this,Gold.class);
startActivity(i2);
break;
case 2:
Intent i3 = new Intent(MainActivity.this,Zinc.class);
startActivity(i3);
break;
}
}
});
}
}
XML
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent" >
</FrameLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="220dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="1dp"
android:background="#000000"/>
</android.support.v4.widget.DrawerLayout>
have you tried :
mDrawerLayout.closeDrawer(drawerListView);
You can add this before calling startActivity()
In continuation to others answers and # Chinmay Dabke question of 'but the drawer closes half then pauses and then closes fully' in one of the comments, here is what you could do:
first as others suggested,
this line is missing. drawer.closeDrawer(navList);
And as far as the pausing of drawer is concerned while closing, you could do something like this.
use a Runnable and a Handler like this:
mRunnable = = new Runnable() {
#Override
public void run() {
//say
selectItem(pos); //Implement your switch case logic in this func
}
}
and then in the onDrawerClosed overrided method
#Override
public void onDrawerClosed(View view) {
if (mRunnable != null) {
mHandler.post(mRunnable);
mRunnable = null;
}
}
Hope this helps!
I would suggest you to use fragments for navigation drawer and to solve this issue of drawer not closing properly, I found this article very useful (using fragments). http://www.michenux.net/android-asynctask-in-fragment-best-pratices-725.html
Call
drawer.closeDrawer(navList);
in onItemClick() method
Try
drawer.closeDrawer(Gravity.START);
Your drawer gravity is start so Use that to close the corresponding drawer
I didn't see any code where you are closing the ListView from drawer... close the ListView Drawer on ListItem click...
navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.closeDrawer(navList);
switch (pos){
case 0:
Intent i = new Intent(MainActivity.this,Aluminium.class);
startActivity(i);
break;
case 1:
Intent i2 = new Intent(MainActivity.this,Gold.class);
startActivity(i2);
break;
case 2:
Intent i3 = new Intent(MainActivity.this,Zinc.class);
startActivity(i3);
break;
}
}
});
You need to close the drawer on list item click
drawer.closeDrawer(navList);
Also what is the use of FrameLayout in your xml. It is not used as a container to add or replace fragments
call the drawer.closeDrawer(navList); function before switch case
use
if(drawer.isDrawerOpen(navList))
{
drawer.closeDrawer(navList);
}
In onResume() and start of onItemClick() method.
or you can try another approach..run a Ui thread when you are selecting drawer item
private void selectDrawerItemItem(final int position){
//Toast.makeText(getApplicationContext(), "ItemClicked", Toast.LENGTH_SHORT).show();
darwer.closeDrawer(navList);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Fragment fragment = new Fragment(Activity.this);
Bundle args = new Bundle();
args.putInt(Fragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame,fragment).commit();
// update selected item and title, then close the drawer
navList.setItemChecked(position, true);
setTitle(" " + navListTitles[position]);
}
}, 200);
// update the main content by replacing fragments
}
I was having the same problem.
I used
mDrawerLayout.closeDrawer(drawerListView);
before starting my new activity. It beautifully slides the drawer back in.
private DrawerLayout mDrawerLayout;
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.closeDrawers();
it works
Here is the code:
Lets say you have the drawer class
in your activity call the class as and make a vaiable and assign it(put the drawer layout within a fragment for smoother user experience)
Drawer drawer;
drawer = (Drawer)getActivity().getSupportFragmentManager().findFragmentById(R.id.theid);
drawer.mDrawerLayout.closeDrawer(Gravity.END);
//End for right and Start for left
Hope it helps
I am currently re-coding most of the back end of my android app in order to follow the design guidelines more closely. Currently I am using all activities and zero fragments. I am trying to switch to fragments in order to use the slide out navigation draw and eventually some sliding tabs.
For navigation right now I have this drop down menu which when an item is clicked launches a new activity:
The "Your Statistics" activity is kind of like the home page, where the user will enter the app too. I also want the user to be able to get back to that "page" from anywhere in the app.
My activity that I plan to run the draw from I have a draw layout called fragment_main:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<ListView
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFF"
android:choiceMode="singleChoice"/>
</android.support.v4.widget.DrawerLayout>
and my activity which loads the drawer layout is:
public class MainDraw extends FragmentActivity {
final String[] data ={"one","two","three"};
final String[] fragments ={
"com.beerportfolio.beerportfoliopro.FragmentOne",
"com.beerportfolio.beerportfoliopro.FragmentTwo",
"com.beerportfolio.beerportfoliopro.FragmentThree"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
//todo: load statistics
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActionBar().getThemedContext(), android.R.layout.simple_list_item_1, data);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
final ListView navList = (ListView) findViewById(R.id.drawer);
navList.setAdapter(adapter);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView){
super.onDrawerClosed(drawerView);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main, Fragment.instantiate(MainDraw.this, fragments[pos]));
tx.commit();
}
});
drawer.closeDrawer(navList);
}
});
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main,Fragment.instantiate(MainDraw.this, fragments[0]));
tx.commit();
}
}
IN my //todo: comment I should load my first "home" fragment there which is my statistics "page" ? And then all the other fragments will be transitioned in and out based on the draw clicks?
Thanks for your help in advance, I want to make sure I am doing this right, I used to code just to get things working which is why I am now re doing a huge chunk of my code. Please share any other fragment tips to that I might need!
First of all read the well written documentation, it answers to your doubts.
I would share my personal pattern to convert existing Activity to Fragment
Create your on abstract Fragment class from which derive all drawer fragments, this can help to group common attributes
Use a method like selectItem() on docs, it helps to explicit do a call at first run (showing the "home" fragment) and then from onItemClick
move inflating XML layout from Activity.onCreate() code to Fragment.onCreateView() (ie setContentView to inflater.inflate(R.layout.my_layout, container, false), in many cases you can copy all code from onCreate() to onCreateView
move initialization code from Activity.onCreate() to Fragment.onActivityCreated(), this is very useful when both Activity (including fragment) and the direct Fragment exist, for example if your app exposes a "Share with" action you continue to have the Activity that inside the XML includes a <fragment/> and the fragment can be created from the drawer, too
if you need to communicate from Activity to Fragment and viceversa I suggest to create an interface and store it inside the 'onAttach()' (see google example)
Action bar items must be hidden when drawer is open, again take a look at example used in doc, here is very useful the interface to communicate from activity to fragment, the main activity can tell if drawer is open and the fragment can call the interface
public interface FragmentActivityStatus {
public boolean isDrawerOpen();
}
The activity
public class MainActivity extends Activity implements FragmentActivityStatus {
#Override
public boolean isDrawerOpen() {
return drawerLayout.isDrawerOpen(drawerList);
}
}
The fragment
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
fragmentActivityStatus = (FragmentActivityStatus)activity;
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
boolean isMenuVisible = !fragmentActivityStatus.isDrawerOpen();
menu.findItem(R.id.my_menu).setVisible(isMenuVisible);
super.onPrepareOptionsMenu(menu);
}
Not related to fragment, in your code you declare class names as string, consider to create a Class array if you refactor packages the code continue to work, then you can call the Class.getName() to obtain the string to pass to Fragment.instantiate()
final Class<?>[] fragments = {
FragmentOne.class,
FragmentTwo.class,
FragmentThree.class};
Then
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main, Fragment.instantiate(MainDraw.this,
fragments[pos].getName()));
tx.commit();
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.