Android 如何在片段中实现 onBackPressed() 和意图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22552653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:10:04  来源:igfitidea点击:

How to implement onBackPressed() & intents in fragment?

androidandroid-intentandroid-fragments

提问by addy123

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 ?

我知道 onBackPressed() 是活动中的一种方法,但是,我想在片段中使用该功能,以便在按下后退按钮时,它会通过 Intent 重定向到另一个活动。有什么解决办法吗?

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

 }

采纳答案by Alok Kulkarni

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

覆盖 onKeyDown 而不是 onBackPressed。不必要 。但这对我有用

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

回答by sirFunkenstine

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

}

回答by Chintan Rathod

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.
  1. 检查您的片段是否已初始化。如果是,则将返回按下事件传递给您的片段。
  2. 如果上述条件未通过,只需将按下返回到您的活动,以便它处理它。

Note

笔记

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

这里条件可以是任何东西。我只是以fragment初始化为例。可能帮不了你。您需要定义自己的条件以将其传递给片段。

Edit

编辑

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

我在 GitHub 上创建了一个示例应用程序来实现 Fragment 的 Back Stack。

Download Fragment Back Stackapplication.

下载片段返回堆栈应用程序。

回答by Priya

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

您可以为片段实现 onKeyListener 并在其中调用下一个活动。我从来没有试过这个。但我希望它可以帮助

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

回答by Shrikant Salunkhe

You need to override onBackPressed method in fragment.

您需要在片段中覆盖 onBackPressed 方法。