How to implement onBackPressed() & intents in frag

2019-01-08 01:27发布

问题:

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

 }

回答1:

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


回答2:

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

}


回答3:

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.



回答4:

You can implement onKeyListener for your fragment and call next activity within that. I've never tried this. But i hope it may help

For Example

fragmentObject.getView().setOnKeyListener( new OnKeyListener()
{
    @Override
    public boolean onKey( View v, int keyCode, KeyEvent event )
    {
        if( keyCode == KeyEvent.KEYCODE_BACK )
        {  
            //your code here


        }
        return false;
    }
} );


回答5:

You need to override onBackPressed method in fragment.