Make intent to another activity inside Fragment ClickListener in Android


When we working with fragment, we want to put click action on item inside. For instance, we have calendar fragment and we want give OnItemClickListener on selected date. Here is a requirement to do that:

1. We need to access Parent Activity from fragment.
2. We can pass into another Activity from onItemClickListener inside fragment.

At this example, we want to pass action into DetailActivity

Here is the solution (inside fragment class):

Step 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * Callback to listener when date is selected
 */
private OnItemClickListener getDateItemClickListener() {
    dateItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
           
            // Create Intent to passing id position to CalendarDetail
            Intent i = new Intent(getActivity().getApplicationContext(),
                    DetailActivity.class);
            startActivity(i);
        }
    };

    return dateItemClickListener;
}


Remember, using getApplicationContext() will give us error:

1
getApplicationContext() is undefined for the type new AdapterView.OnItemClickListener(){} is undefined for the type new   AdapterView.OnItemClickListener(){}

So, to get Activity inside fragment Listener, we should use “getActivity()”.

Step 2
Then we can wrap this listener into fragment, ex:

1
dateGridFragment.setOnItemClickListener(getDateItemClickListener());

Voila! Now we can make whatever action inside OnItemClickListener fragment 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.