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

我知道onBackPressed()是一个活动中的方法,但是我想使用片段中的function,当按下返回button时,它通过Intent被redirect到另一个活动。 有没有解决这个问题?

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

Solutions Collecting From Web of "如何在片段中实现onBackPressed()和意图?"

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

您可以使用callback接口与片段进行交互。 在您的活动中添加以下内容:

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

在你的片段中添加以下内容:

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

就在这里。 你应该像这样执行。

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

说明

  1. 检查你的片段是否被初始化。 如果是这样,那么传回新闻事件到你的片段。
  2. 如果上述条件没有通过,只需传回给您的活动,以便它将处理它。

注意

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

编辑

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

下载Fragment Back Stack应用程序。

你可以为你的片段实现onKeyListener,并调用其中的下一个活动。 我从来没有试过这个。 但我希望这可能会有所帮助

例如

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

您需要重写片段中的onBackPressed方法。