Thursday, January 8, 2015

Android: Calling Toast in Fragment class


A quick way to pop up messages within Android application is to use the Toast class. This doesn't require users to click any button for it to go away and helps in debugging Android interaction. The class reference can be found at developers.android.com. An introduction to use of Toast can be found at developer.android.com. It shows the basics of Toast and how to position it.

Syntax for the Toast is straight forward as the static function makeText is used. Syntax:

makeText(Context context, int resId, int duration)
and
makeText(Context context, CharSequence text, int duration)


Both gets the Context as the 1st param where this is commonly called via  the getApplicationContext() function from the Activity class. This is common in examples to use the ListView, e.g. Vogella.

Following error is given if this function is used outside of an Activity class;

can't resolve method getApplicationContext()

Sometimes, a piece of the user interface is separated from the Activity into smaller chunk called the Fragment class. For example, getting the Toast to pop up messages in the class that extends Fragment class involves getting the Activity context to be used in the Toast 1st param. Use the function getActivity( ) in Fragment class instead of getApplicationContext( ) function in Activity class.

In the example below, the Toast will contain message from text retrieved in the ListView.

ListView lv = (ListView) rootView.findViewById(R.id.listview_attendance);
        lv.setAdapter(mAttendanceAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                int duration = Toast.LENGTH_SHORT;
                String text = (String)parent.getItemAtPosition(position);

                Toast toast = Toast.makeText(getActivity(), text, duration);
                toast.show();

            }
        });


---
Project build: minSdkVersion 10

No comments:

Blog Archive