Android Program to Demonstrate Navigation Using Fragments

Here is source code of the Program to Demonstrate Navigation Using Fragments in Android using Java. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

Here i demonstrate navigation drawer along with fragments in Android , fragments are extremely useful because a fragment is an independent component which can be used by an activity. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts.A fragment also make it easy to reuse components in different layouts. In this following code the Class_Fragment can be used again and again to show a different layout each time.

Main Activity

package com.example.navigation_drawer1;
 
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
 
@SuppressLint("NewApi")
public class MainActivity extends Activity {
    private String[] titles;
    private DrawerLayout layout_drawer;
    private ListView drawer_content;
    private ActionBarDrawerToggle action_bar_toggle;
    private CharSequence title;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        title = getActionBar().getTitle();
        titles = getResources().getStringArray(R.array.operating_systems);
        layout_drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer_content = (ListView) findViewById(R.id.left_drawer);
 
        drawer_content.setAdapter(new ArrayAdapter<String>(this,
                R.layout.fragment_layout, R.id.textView_fragment, titles));
        drawer_content.setOnItemClickListener(new DrawerItemClickListener());
 
        action_bar_toggle = new ActionBarDrawerToggle(this, /* Main Activity */
        layout_drawer, /* layput for navigation drawer */
        R.drawable.ic_drawer, R.string.drawer_open, /* on open drawer */
        R.string.drawer_close /* on close drawer */) {
 
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(title);
            }
 
            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle("Open Drawer");
            }
        };
 
        layout_drawer.setDrawerListener(action_bar_toggle);
 
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
 
    }
 
    private class DrawerItemClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView parent, View view, int position,
                long id) {
            selectItem(position);
        }
    }
 
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        action_bar_toggle.syncState();
    }
 
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        action_bar_toggle.onConfigurationChanged(newConfig);
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (action_bar_toggle.onOptionsItemSelected(item)) {
            return true;
        }
        switch (item.getItemId()) {
        case R.id.action_settings:
            Toast.makeText(this, "settings", Toast.LENGTH_LONG).show();
            break;
 
        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }
 
    private void selectItem(int position) {
        Class_Fragment fragment = new Class_Fragment();
        Bundle args = new Bundle();
        args.putInt(Class_Fragment.ARG_OS, position);
        fragment.setArguments(args);
        android.app.FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.content_frame, fragment).commit();
 
        drawer_content.setItemChecked(position, true);
        getActionBar().setTitle((titles[position]));
        layout_drawer.closeDrawer(drawer_content);
    }
 
}

Class_Fragment

package com.example.navigation_drawer1;
 
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
 
class Class_Fragment extends Fragment {
    public static final String ARG_OS = "OS";
    private String string;
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_layout, null);
        TextView textView = (TextView) view
                .findViewById(R.id.textView_fragment);
        textView.setText(string);
        return view;
    }
 
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
 
    @Override
    public void setArguments(Bundle args) {
        string = args.getString(ARG_OS);
    }
}

The array operating_systems that is being used is defined in Strings.xml , include the following code here also.
Strings.xml

advertisement
advertisement
<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <string name="app_name">Navigation_Drawer1</string>
    <string name="action_settings">Settings</string>
    <string name="action_update">Update</string>
    <string name="drawer_open">Open Drawer</string>
    <string name="drawer_close">Close Drawer</string>
    <string name="hello_world">Hello world!</string>
 
    <string-array name="operating_systems">
        <item>Android</item>
        <item>iPhone</item>
        <item>Windows Mobile</item>
        <item>Linux </item>
        <item>Windows 7.0</item>
        <item>Windows 8.0</item>
        <item>Windows 8.1</item>
        <item>Chrome OS</item>
        <item>Unix</item>
        <item>Symbian</item>
    </string-array>
 
</resources>

Screenshot_2013-12-06-03-48-25

Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.

If you wish to look at all Tutorials, go to Java Android Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.