How to implement onBackPressed() & intents in fragment?

I know that onBackPressed() is a method in activity but, I want to use the functionality in fragments such that when back button is pressed, it gets redirected to another activity via Intent. Is there any solution to this ?

public class News_Events_fragment extends Fragment {
ProgressDialog pd;
ListView lv1;
SharedPreferences sharedPreferences = null;
int NotiCount;
TextView txt_title, txt_msg, textView;
Context context;
Intent intent ;
ArrayList<SliderMsgTitleModel> CurrentOfficersPastList;
NewsActivityAdapter pastAdapter;

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

    context = (Context) getActivity();

    View rootView = inflater.inflate(R.layout.activity_news, container, false);

    new AsyncTask<Void, Void, ArrayList<SliderMsgTitleModel>>() {

        protected void onPreExecute() {
            pd = new ProgressDialog(getActivity());
            pd.setCancelable(true);
            pd.setTitle("UPOA");
            pd.setMessage("Please wait,loading the data...");
            pd.show();
        }

        @Override
        protected ArrayList<SliderMsgTitleModel> doInBackground(
                Void... params) {
            System.out.println("In Background");
            CurrentOfficersPastList = new ArrayList<SliderMsgTitleModel>();
            // display view for selected nav drawer item
            ParseQuery<ParseObject> query = ParseQuery.getQuery("message");
            query.whereEqualTo("featured_status", true);
            // query.whereEqualTo("push_status", true);

            query.orderByDescending("updatedAt");

            query.selectKeys(Arrays.asList("title"));
            query.selectKeys(Arrays.asList("message"));
            try {
                query.setCachePolicy(ParseQuery.CachePolicy.NETWORK_ELSE_CACHE);
                List<ParseObject> results = query.find();
                for (int i = 0; i < results.size(); i++) {
                    ParseObject object = results.get(i);
                    CurrentOfficersPastList.add(new SliderMsgTitleModel(
                            object.getString("title"), object
                                    .getString("message")));
                    System.out.println("title is=="
                            + object.getString("title") + "&& message is"
                            + object.getString("message") + "size is"
                            + CurrentOfficersPastList.size());

                }
            } catch (Exception e) {
                e.getMessage();
            }
            pd.dismiss();

            return CurrentOfficersPastList;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void onPostExecute(ArrayList<SliderMsgTitleModel> value) {

            pd.dismiss();
            /*Intent ent = new Intent(getActivity(), NewsActivity.class);
            ent.putExtra("NEWSLIST", (ArrayList<SliderMsgTitleModel>) value);
            startActivity(ent);
            System.out.println("Value is" + value.size());*/

            CurrentOfficersPastList = new ArrayList<SliderMsgTitleModel>();
            CurrentOfficersPastList = value;
            lv1 = (ListView) getActivity().findViewById(R.id.list_title);
            pastAdapter = new NewsActivityAdapter(getActivity(), R.layout.activity_news_txt, CurrentOfficersPastList);
            lv1.setAdapter(pastAdapter);

        }
    }.execute();

    return rootView;
}

public void onBackPressed() {
    // TODO Auto-generated method stub
    //super.onBackPressed();
    //Toast.makeText(getApplicationContext(), "click",2000).show();
            String cameback="CameBack";
            intent = new Intent(getActivity(),HomeActivity.class);
            intent.putExtra("Comingback", cameback);
            startActivity(intent);
}

 }

Solution 1:

You can interact with the fragment using a callback interface. In your activity add the following:

public class MyActivity extends Activity {

    protected OnBackPressedListener onBackPressedListener;

    public interface OnBackPressedListener {
        void doBack();
    }

    public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
        this.onBackPressedListener = onBackPressedListener;
    }

    @Override
    public void onBackPressed() {
        if (onBackPressedListener != null)
            onBackPressedListener.doBack();
        else
            super.onBackPressed();
    } 

    @Override
    protected void onDestroy() {
        onBackPressedListener = null;
        super.onDestroy();
    }
}

In your fragment add the following:

public class MyFragment extends Fragment implements MyActivity.OnBackPressedListener {

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
         ((MyActivity) getActivity()).setOnBackPressedListener(this);
    }

    @Override
    public void doBack() {
        //BackPressed in activity will call this;
    }

}

Solution 2:

Yes, There is. You should implement like this.

@Override
public void onBackPressed() {
    if (fragment != null)
        //user defined onBackPressed method. Not of Fragment.
        fragment.onBackPressed();
    } else {
        //this will pass BackPress event to activity. If not called, it will
        //prevent activity to get BackPress event.
        super.onBackPressed();
    }   
}

Explanation

  1. Check whether your fragment is initialized or not. If it is, then pass on back press event to your fragment.
  2. If above condition not passed, just pass back press to your activity so that it will handle it.

Note

Here condition can be anything. I just take fragment initialization as an example. May be that can't be helped you. You need to define your own condition to pass it to fragment.

Edit

I created a sample application on GitHub to implement Back Stack of fragment .

Download Fragment Back Stack application.

Solution 3:

Override onKeyDown instead of onBackPressed. Not necessarily . But this works for me

public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                String cameback="CameBack";
                intent = new Intent(getActivity(),HomeActivity.class);
                intent.putExtra("Comingback", cameback);
                startActivity(intent);
                return true
    }
            return false;
}