how to display navigation bar to open link on fragment - android

i want to display a list or some kind of menu in navigation drawer at runtime. I have one single activity in which i put fragment using frame layout. This fragment contains Webview. Whenever user clicks on navigation item, then webview opens its alternative link. I successfully received response from Retrofit 2.3, but now i dont know how to achieve this
public void onResponse(Call<List<NavBarResult>> call, Response<List<NavBarResult>> response) {
List<Result> result = response.body();
//what to do here ?
}
#Override
public void onFailure(Call<List<NavBarResult>> call, Throwable t) {
//error messages here
}
My JSON API look like:
[
{
menulist_id: "1",
mname: "Item 1",
mlink: "http://example.com/technology/",
},
{
menulist_id: "2",
mname: "Item 2",
mlink: "http://example.com/sports/",
}
]
I want to work like that all menu's items work automatically even if we change the data from API. Thanks in advance.

Possible duplicate.
Android - Add bottom navigation view dynamically
How can I add a menu dynamically to bottom navigation view?
You can dynamically get the menu from your navigation view, then add a new menu item with you JSON response.
In your OnNavigationItemSelectedListener you can change the URL of your webview.
EDIT 1
Maybe I misunderstood something. Do you want to populate a Navigation Bar with your JSON response ? In that case, my links above can help you.
Do you want to populate a Navigation Drawer with your JSON response ?
In that case you should begin read this : https://developer.android.com/training/implementing-navigation/nav-drawer.html
Edit your activity layout :
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
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:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
content_frame will contain your fragment with a WebView.
left_drawer will contain your dynamics links.
Get the left_drawer :
mDrawerList = (ListView) findViewById(R.id.left_drawer);
When you get your JSON response just set a adapter to your mDrawerList :
public void onResponse(Call<List<NavBarResult>> call, Response<List<NavBarResult>> response) {
// result is a private List<Result> attribute of the class.
result = response.body();
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<Result>(this,
android.R.layout.simple_list_item_1, result));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
This way, your Drawer Layout will be populated with your JSON response dynamically.
Then you just have to define your OnItemClickListener to call a new fragment when you click on an item of your list.
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
MyFragment is not developp here but it would contain a webView and wait for a ARG_LINK that should be an URL to display in its webView.
private void selectItem(int position) {
// Create a new fragment and specify the link to show based on position
Fragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putString(MyFragment.ARG_LINK, result.get(position).getUrl());
fragment.setArguments(args);
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
// Highlight the selected item and close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mDrawerList);
}
Hope it help you this time !

You can add a navigation view in your navigation drawer then when you are receiving the items from the API you can add Items to the menu see below code to add the items from the menu.
final Menu menu = navigationView.getMenu();
//Here you should add the length of your json array instead 'i' .
for (int i = 1; i <= 3; i++) {
menu.add("Runtime item "+ i);
}

Related

change current active state of bottom tab on a list item click in a fragment

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Data data = mListDatas.get(i);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ThirdFragment thirdFragment = new ThirdFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("detail", data);
thirdFragment.setArguments(bundle);
transaction.replace(R.id.content,ThirdFragment).addToBackStack(null).commit();
BottomNavigationView navigation = (BottomNavigationView)view.findViewById(R.id.navigation_bottomview);
navigation.setSelectedItemId(R.id.navigation_third_tab);
}
});
In the above code i need to open a new fragment on the bottom tab from a list item click,
i am able to open a new fragment but the current tab remains unchanged i.e, after redirecting to the third fragment on third bottom tab ,the current tab i.e, Second Tab is active.
How can i change the active state of bottom tab from second tab to third tab on the list item click ??
Your activity needs to implement the BottomNavigationView.OnNavigationItemSelectedListener. This can be done simply by adding implements BottomNavigationView.OnNavigationItemSelectedListener after your class name, this is done so you can get the click callback whenever one of the bottom menu items are clicked on.
Then you need to override the onNavigationItemSelected function so add the following code to your activity.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.tab_1:
handleFragmentChange(Fragment_1.newInstance());
return true;
}
return false;
}
Also add navigation.setOnNavigationItemSelectedListener(this); in the same activity once you have found the view using findViewById. This is done so that the system knows that your class is handling the event when a bottom menu is clicked so it calls the above function in your class.
The return true is what notifies the android system that it needs to switch the tab.
if this code locates in fragment then you need to replace
BottomNavigationView navigation = view.findViewById(R.id.navigation_bottomview);
navigation.setSelectedItemId(R.id.navigation_third_tab);
before
...commit();
and add getRootView() because your BottomNavigationView locate inside main container - root activity
BottomNavigationView navigation = view.getRootView().findViewById(R.id.navigation_bottomview);
navigation.setSelectedItemId(R.id.navigation_third_tab);

Implementing SwipeView, SwipeRefreshlayout, and Navigation Drawer in one activity

as the title suggests, I'm trying to implement all of these features at once. Originally I had a fully functioning side-nav with a SwipeRefreshLayout which holds a list view (using a custom list adapter). I then added a ViewPager inside of the SwipeRefreshLayout, and everything mostly works…except that as I swipe the list view does not appear in the new 'tabs' sometimes. Most of the time I see the first page and list view, I swipe right, nothing, I swipe right, nothing, I swipe left, list view, I swipe to the beginning, nothing.
I should add that everything is entirely dynamic, the navigation items are received from my server (which is also the number of pages) and each page has a custom list adapter with different list items. All of this dynamic information seems to be received and adapted correctly per page swipe etc.
Now for the code!
Drawer layout with swiperefreshlayout and view pager embedded. "drawer.xml"
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.SwipeRefreshLayout>
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/grey_lighter"
android:dividerHeight="1dp"
android:background="#FFFFFF"/>
</android.support.v4.widget.DrawerLayout>
Listview which holds the custom list items created dynamically in the activity "dashboard.xml":
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LV_dashboard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1" >
</ListView>
Now for the fragment activity :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this.getApplicationContext();
navItems = new ArrayList<String>();
this.setContentView(R.layout.drawer);
mMerchantIds = Session.get().getMerchID(); //array retrieved from cache used for api
mCustomerPagerAdapter = new CustomerPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCustomerPagerAdapter);
mTitle = mDrawerTitle = getTitle();
mNavTitles = getResources().getStringArray(R.array.nav_array); //I realize this isn't dynamic, I haven't gotten around to that just yet.
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
connection = new WiselyRequest();
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.nav_item, mNavTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
This branches off into two parts, we'll start with the Drawer:
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments (this is not what the pager does)
Fragment fragment = null;
fragment = new CustomerFragment();
Bundle args = new Bundle();
args.putString(KEY_MERCHANT_ID, (mMerchantIds.get(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
mDrawerList.setItemChecked(position, true);
setTitle(mNavTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
Here is the view pager:
public class CustomerPagerAdapter extends FragmentPagerAdapter {
public CustomerPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new CustomerFragment();
Bundle args = new Bundle();
Log.d("Wisely", "merchants: "+mMerchantIds.get(i));
args.putString(KEY_MERCHANT_ID, (mMerchantIds.get(i))); // Our object is just an integer :-P
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// For this contrived example, we have a 100-object collection.
return mMerchantIds.size(); //equal to the number of merchantss (that many customer objects)
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
Here is the customer fragment that both the drawer and pager are utilizing and where on refresh is handled:
public class CustomerFragment extends Fragment implements OnRefreshListener {
private View rootView;
SwipeRefreshLayout swipeLayout;
public CustomerFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
String merchantID = args.getString(KEY_MERCHANT_ID);
if(connection.checkConnectivity(getApplicationContext())){
getRecentCustomers(API.getRecentCustomers()+"?merchant_id="+merchantID); //api call works totally fine, and correctly sets up the adapter
}
else
Toast.makeText(DashboardActivity.this, "Need to be connected to the internet!", 4000).show();
rootView = inflater.inflate(R.layout.dashboard, container, false);//inflates the dashboard
swipeLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);
registerClickCallback(rootView);
return rootView;
}
#Override
public void onRefresh() {
if(connection.checkConnectivity(getApplicationContext()))
reloadActivity(); //literally turns the activity on and off without animation
else
Toast.makeText(DashboardActivity.this, "Need to be connected to the internet!", 4000).show();
}
I believe the issue exits in my layouts, not in the list adapter or customer fragment which seem to be working fine (every time I swipe to a new page the api is called and the correct data is put into the list view. I just can't see it. Also I realize that the navdrawer is not dynamic, but my bigger issue at the moment is being able to swipe through multiple list views on pages. When I change my customerFragment to inflate a simple text view with a number in it, it seems to work fine, except that the first page never goes away, other pages just pile on top of it (I think this has to do with the framelayout in the drawer but removing it breaks the code because my nag drawer relies on it). Any suggestions?
I think, you will have to create your own classes extending DrawerLayout or ViewPager.
Inside of your classes you have to Override methods:
onInterceptTouchEvent() - here you evaluate TouchEvent and return true, if you are intercepting it (not passing to the child View)
You have to tweak the conditions of intercepting based on what you are trying to achieve.
Guide is here:
http://developer.android.com/training/gestures/viewgroup.html

Call other Fragment from dropDown of ActionBar

In my app I have added a DropDown Spinner in ActionBar and now am not able to make out - how to change the bottom part on each drop down selected. In my activity_main.xml layout (Home), contains only a Fragment that shows a list. I am looking for is, to create other UI screens also as Fragment and change the placed Fragment on every dropDown selected. I mean Home page has fragment_main.xml, dropDown setting is selected then show setting_fragment.xml and so on. My main is :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" >
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
class="terryconsulting.servicestation.AppointListFragment"
android:id="#+id/main_fragment"
/>
</FrameLayout>
In MainActivity class, I have implemented ActionBar.OnNavigationListener which called earlier PlaceholderFragment that just showed Hello World text on the screen.
#Override
public boolean onNavigationItemSelected(int position, long id) {
// When the given dropdown item is selected, show its contents in the
// container view.
//getFragmentManager().beginTransaction()
// .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
// .commit();
return true;
// http://www.vogella.com/tutorials/AndroidActionBar/article.html --- ACTIONBAR ACTION
}
// As AppointListFragment is added in this activity, so need to implement this listener here
#Override
public void onFragmentInteraction(Uri uri) {
System.out.println("Into onFragmentInteraction. URL - " + uri);
return;
}
WHERE I AM STUCK :- I am not able to make out how to call/set SettingFragment when setting is selected from drop down. And from setting when Home icon is pressed go back to home page with AppointListFragment on it ???
What I am thinking & asking of, is it possible & practical ? I think it should be, as calling Setting as an Activity with its own ActionBar would not be best solution.
Please guide me with this, I have searched many tutorials but couldn't find this situation or examples with NavigationSelection & Fragments any where.
fragments in XML layouts are meant to be static ones. I'm pretty it's possible somehow to make them work, but for dynamic generated/created/removed you want to do everything in Java.
said that, first you remove the <fragment from your XML, then on your activity creation:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(... your xml layout ... );
// fragments are auto-re-created on rotation,
// so only create/put in layout one if not rotating
if(savedInstanceState == null){
// I'm assuming here your first fragment is position 0
gotoFragment(0);
}
}
then on each selection is just call to the new one:
#Override
public boolean onNavigationItemSelected(int position, long id) {
gotoFragment(position);
return true;
}
and here is the general method to change the fragments on the screen.
private void gotoFragment(int position){
Fragment f = getFragmentManager().findFragmentByTag("position_" + position);
if(f == null){
switch(position){
case values:
f = // create here new object of your fragment for each position
}
}
getFragmentManager().beginTransaction()
.replace(R.id.container, f, "position_" + position)
.commit();
}

get selected item - ListView Android

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
}

How do organize an app using fragments?

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();

Categories

Resources