Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}

 }
like image 746
addy123 Avatar asked Mar 21 '14 07:03

addy123


People also ask

How do I use onBackPressed activity?

In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so. Otherwise, don't exit.

How do I go back from fragment to activity?

You can get a reference to the FragmentActivity by calling getActivity() on your current Fragment and then call from the Activity retrieved onBackPressed() method.

How do I disable back press in fragment?

Here is the new way you can manage your onBackPressed() in fragment with the new call back of activity: // Disable onBack click requireActivity(). onBackPressedDispatcher. addCallback(this) { // With blank your fragment BackPressed will be disabled. }


2 Answers

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;
    }

}
like image 109
sirFunkenstine Avatar answered Oct 24 '22 06:10

sirFunkenstine


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.

like image 45
Chintan Rathod Avatar answered Oct 24 '22 07:10

Chintan Rathod