Technology10/14/2019

Navigation Menu

Sponsored Intelligence Dispatch




Create a new Navigation Drawer app


I will create a new android application by selecting Navigation Drawer activity in Android Studio. 



Navigation Menu

I will go step by step and tell you about the application we are going to build. First, I will finish the navigation menu layout.

If you open activity_main.xml file at app/res/layout directory, you can see the code for NavigationMenu.



    <android.support.design.widget.NavigationView

        android:id="@+id/nav_view"

        android:layout_width="wrap_content"

        android:layout_height="match_parent"

        android:layout_gravity="start"

        android:fitsSystemWindows="true"

        app:headerLayout="@layout/nav_header_main"

        app:menu="@menu/activity_main_drawer" />

In the above snippet in the last line app:menu="@menu/activity_main_drawer" which says that the menu for this is located at  menu directory in the res folder. So now let us edit the menu items.

Open the activity_main_drawer.xml file and place the following code in it.



<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">

        <item

            android:id="@+id/home"

            android:icon="@drawable/ic_school_black_24dp"

            android:title="Home" />

        <item

            android:id="@+id/timeTable"

            android:icon="@drawable/ic_chrome_reader_mode_black_24dp"

            android:title="Time Table" />

        <item

            android:id="@+id/examSchedule"

            android:icon="@drawable/ic_schedule_black_24dp"

            android:title="Exam Schedule" />

        <item

            android:id="@+id/attendence"

            android:icon="@drawable/ic_assessment_black_24dp"

            android:title="Attendence" />

        <item

            android:id="@+id/result"

            android:icon="@drawable/ic_timeline_black_24dp"

            android:title="Results" />

    </group>

    <item android:title="Social">

        <menu>

            <item

                android:id="@+id/fb"

                android:icon="@drawable/facebook"

                android:title="Facebook" />

            <item

                android:id="@+id/gplus"

                android:icon="@drawable/googleplus"

                android:title="Google +" />

            <item

                android:id="@+id/twitter"

                android:icon="@drawable/twitter"

                android:title="Twitter" />

            <item

                android:id="@+id/youtube"

                android:icon="@drawable/youtube"

                android:title="Youtube" />

            <item

                android:id="@+id/github"

                android:icon="@drawable/github"

                android:title="Github" />

        </menu>

    </item>

</menu>

If you look at the above code, I created a menu using menu, item, and group.

menu which is the root element and it can have sub child’s/sub elements like itemand group.

item which is the single menu item, we can divide/separate the menu by creating an another menu as the sub-child of item element. I also gave a title to the sub menu as ‘Social’ .



In the above screenshots, you can see an icon beside each menu item, that can be set using the android icon attribute android:icon="@drawable/image_name", these icons are either android default images or you can download any icon of your wish and use them. The social network icons I used are from https://icons8.com/ the other icons are default android icons.

So now the NaviginationMenu is completed, now I will link this menu item clicks to its related fragment.

In the MainActivity.java file,

I initialized the NavigationView using the following couple of lines,


NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

navigationView.setNavigationItemSelectedListener(this);



I will handle the menu click items in the following lines of code,


 public boolean onNavigationItemSelected(MenuItem item) {

        int id = item.getItemId();

        Fragment fragment = null;

        Bundle bundle = new Bundle();

        if (id == R.id.home) {

            fragment = new HomeFragment();

        } else if (id == R.id.timeTable) {

            fragment = new TimeTableFragment();

        } else if (id == R.id.examSchedule) {

            fragment = new ExamScheduleFragment();

        } else if (id == R.id.attendence) {

            fragment = new AttendenceFragment();

        } else if (id == R.id.result) {

            fragment = new ResultFragment();

        } else if (id == R.id.fb) {

            bundle.putString("url", "https://www.facebook.com/androidcodeblock");

            fragment = new WebViewFragment();

            fragment.setArguments(bundle);

        } else if (id == R.id.gplus) {

            bundle.putString("url", "https://plus.google.com/u/0/s/android%20codeblock/");

            fragment = new WebViewFragment();

            fragment.setArguments(bundle);

        } else if (id == R.id.twitter) {

            bundle.putString("url", "https://www.twitter.com/");

            fragment = new WebViewFragment();

            fragment.setArguments(bundle);

        } else if (id == R.id.github) {

            bundle.putString("url", "https://github.com/saliljha1993/NavigationDrawerPractice/");

            fragment = new WebViewFragment();

            fragment.setArguments(bundle);

        } else if (id == R.id.youtube) {

            bundle.putString("url", "https://www.youtube.com/");

            fragment = new WebViewFragment();

            fragment.setArguments(bundle);

        }

        if (fragment != null) {

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

            ft.replace(R.id.content_frame, fragment);

            ft.commit();

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        drawer.closeDrawer(GravityCompat.START);

        return true;

    }

Here I got the id of each menu item and use that id to check and start a new fragment and for social links, I also pass the URL of the appropriate social network link for Android Hunger and start a new activity, here I use same WebViewFragment to load all of my web pages of different social networks.

Now let us see each of the fragment, and what is does.



Navigation Menu item – HomeFragment

In the HomeFragment.java file in the onCreate function, I initialize the layout(R.layout.home) for this fragment.



public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.home, container, false);

    }





In the above screenshots, I nested different layouts, both horizontal and vertical scroll view, a custom view to draw an horizontal dividing line and many more.



I used a  LinearLayout to show name, semester, department and registration number, the layout is as follows,




    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_margin="5dp">

        <LinearLayout

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:orientation="vertical">

            <TextView

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="Avinash"

                android:textAppearance="?android:attr/textAppearanceMedium" />

            <TextView

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="Dept. of CSE"

                android:textAppearance="?android:attr/textAppearanceMedium" />

        </LinearLayout>

        <View

            android:layout_width="0dp"

            android:layout_height="0dp"

            android:layout_weight="1" />

        <LinearLayout

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:orientation="vertical">

            <TextView

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="Semester 3"

                android:textAppearance="?android:attr/textAppearanceMedium" />

            <TextView

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="1234567890"

                android:textAppearance="?android:attr/textAppearanceMedium" />

        </LinearLayout>

    </LinearLayout>

Next, I used a View attribute to display a horizontal line just as a separator,



    <View

        android:layout_width="match_parent"

        android:layout_height="1pt"

        android:layout_margin="8pt"

        android:background="#a7a9ef"></View>

Then a simple TextView which says Important Info.


<TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Important Info" />

Now a ScrollView with some TextView’s in it. As you know ScrollView should have only one child, so I use a LinearLayout and place all the TextView there.




    <ScrollView

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_weight="1">

        <LinearLayout

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:orientation="vertical">

            <TextView

                android:layout_width="match_parent"

                android:layout_height="150dp"

                android:layout_marginBottom="5dp"

                android:background="#e53935"

                android:gravity="center"

                android:text="WebTechnologies assignment submission tommorrow"

                android:textColor="#FFF"

                android:textSize="30sp" />

           <TextView

             .....

             .....

             .....

        </LinearLayout>

    </ScrollView>



Next I will display a HorizontalScrollView to show some buttons,



    <HorizontalScrollView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_gravity="center"

        android:gravity="center">

        <LinearLayout

            android:layout_width="wrap_content"

            android:layout_height="wrap_content">

            <Button

                android:id="@+id/btnTimeTable"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_margin="2dip"

                android:background="#ffff4444"

                android:padding="2dip"

                android:text="Time Table"

                android:textColor="#FFF" />

            <Button

            ......

            ......

            ......

        </LinearLayout>

    </HorizontalScrollView>

I will now handle this button clicks in its Fragment(HomeFragment).

Initialise the buttons, in viewCreated() method, place the following lines.


Button btn = (Button) getView().findViewById(R.id.btnID);

I will set a click listener to it,


btn.setOnClickListener(this);

So now I will let the fragment implement click listeners.


public class HomeFragment extends Fragment implements View.OnClickListener {

....}

Now it will create a new method onClick,



    public void onClick(View v) {

        Fragment fragment = null;

        switch (v.getId()) {

            case R.id.btnTimeTable:

                fragment = new TimeTableFragment();

                break;

            ......

            ......

        }

        getActivity().getSupportFragmentManager().beginTransaction()

                .replace(R.id.content_frame, fragment)

                .addToBackStack(null)

                .commit();

    }

So now when a button is clicked I will start its related Fragment.



Navigation Menu item – TimeTableFragment
In the TimeTableFragment.java file in the onCreate function, I initialize the layout(R.layout.timetable) for this fragment.


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.timetable, container, false);

    }

Let us see timetable.xml file at res/layout/timetable.xml



The component tree of the layout,

Here the main part is the TableLayout where I display the time table with subjects and time and below it a   LinearLayout to display the subject full names.

Also placed these two Layouts in a ScrollView, and to make the ScrollView center, I used RelativeLayout to set android:layout_centerVertical="true" as ScrollView’s attribute.

TableLayout have multiple child elements TableRow’s and here I placed someTextView’s in its rows.


<TableLayout

android:layout_width="match_parent"

android:layout_height="wrap_content">

    <TableRow...>

    <TableRow...>

    <TableRow...>

    .....

</TableLayout>



<TableRow

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:background="#a7a9ef"

    android:gravity="center"

    android:padding="2dip">

    <TextView...>

    <TextView...>

<TableRow>

Next, a LinearLayout of TextView’s to display each subject’s name.



<LinearLayout

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_gravity="start"

    android:layout_marginTop="10dip"

    android:orientation="vertical"

    android:textAlignment="textStart">

    <TextView...>

    <TextView...>

</LinearLayout>



Navigation Menu item – ExamScheduleFragment
In the ExamScheduleFragment.java file in the onCreate function, I initialize the layout(R.layout.examschedule) for this fragment.


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.examschedule, container, false);

    }

Let us see examschedule.xml file at res/layout/examschedule.xml





This layout is pretty simple, it just consists of TextView’s all in a ScrollView



Below is the layout snippet,


<RelativeLayout

        android:layout_width="fill_parent"

        android:layout_height="fill_parent">

        <ScrollView

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:layout_centerVertical="true">

            <LinearLayout

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                android:layout_gravity="start"

                android:orientation="vertical">

            <TextView...>

            <TextView...>


             ...

             ...

Navigation Menu item – AttendenceFragment
In the AttendenceFragment.java file in the onCreate function, I initialize the layout(R.layout.attendence) for this fragment.



public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.attendence, container, false);

    }





So here, I just used a simple Spinner to select the semester and then in display that semester’s attendance in TextView. The Spinner is something like which you can call it a dropdown too. There are some methods on Spinner like ononItemSelected so we can do something when the item in the Spinner is changed. Let’s see all that cool stuff now.

So in the AttendenceFragment I initialize this Spinner,



Spinner spinner = (Spinner) view.findViewById(R.id.semSpinner);

also set an adapter to it, to show some items in the Spinner.


ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),

        R.array.semisters, android.R.layout.simple_spinner_item);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinner.setAdapter(adapter);

Here I stored the Spinner item list in a separate file called srings.xml where we can store all the strings used in our app.

Open /app/res/values/strings.xml and add the following string array.


<string-array name="semisters">

    <item>Semister 1</item>

    <item>Semister 2</item>

    <item>Semister 3</item>

</string-array>

So I used this array as R.array.semisters to set the adapter.

So now, I displayed the Spinner with some items, I also need to listen to the item change in the Spinner. So I use item selected listener on this Spinner.


spinner.setOnItemSelectedListener(this);

and a method to use when implementing AdapterView.OnItemSelectedListener


@Override

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    String semester = parent.getItemAtPosition(position).toString();

    if (semester.equals("Semister 1")) {

        textView.setText("Your attendence for this Semister is 82%");

    } else if (semester.equals("Semister 2")) {

        textView.setText("Your attendence for this Semister is 86.8%");

    } else if (semester.equals("Semister 3")) {

        textView.setText("Your attendence for this Semister is 73.8% as of now.");

    }

}

So when the semester changes, I just updated the TextView with some static value for attendance.

Navigation Menu item – ResultFragment
The Result screen is very similar to the previous screen attendance, here I use the same layout, the only change is the TextView when the Spinner item is changed.

See the following snippet,



@Override

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    String semester = parent.getItemAtPosition(position).toString();

    if (semester.equals("Semister 1")) {

        textView.setText("SGPA: 6.2");

    } else if (semester.equals("Semister 2")) {

        textView.setText("SGPA: 6.6 CGPA: 6.4");

    } else if (semester.equals("Semister 3")) {

        textView.setText("Not yet available");

    }

}

Navigation Menu item – WebViewFragment
In the Navigation Menu, there are some social links like Facebook, G+, Twitter, YouTube, and Github. So when these items are pressed I will load up its related web page. A detailed explanation of implementing WebView in Android is discussed in my previous post.

So in the onNavigationIemSelected method inMainActivity which I just discussed, I will just pass the URL of the respective social network site to WebViewFragmentwhich then loads the web page.

So in WebViewFragment I will read the URL sent,




String url = this.getArguments().getString("url");

and pass it to a function callWebClient which calls the WebViewClient,




callWebClient(url);

and the callWebClient(url); function,


private void callWebClient(String urll) {

    wv.setWebViewClient(new myWebViewClient());

    wv.getSettings().setLoadsImagesAutomatically(true);

    wv.getSettings().setJavaScriptEnabled(true);

    wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

    wv.loadUrl(urll);

}

Deep Structural Diagnostics.

Mastering JSON is only the first step. Use our industrial-grade workbench to format, validate, and synthesize models for your production APIs.

Sponsored Infrastructure

Industrial Analysis Active