如何实现onBackPressed()&片段意图?

时间:2014-03-21 07:22:26

标签: android android-intent android-fragments

我知道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);
}

 }

5 个答案:

答案 0 :(得分:34)

您可以使用回调界面与片段进行交互。在您的活动中添加以下内容:

Array
(
    [bla123] => Array
        (
            [0] => 2
            [1] => 3
            [2] => 2
            [3] => 2
            [4] => 2
            [5] => 2
            [6] => 2
            [7] => 2
            [8] => 2
        )

    [12xye] => Array
        (
            [0] => 4
            [1] => 3
            [2] => 3
            [3] => 2
            [4] => 2
            [5] => 4
            [6] => 2
            [7] => 2
            [8] => 2
        )

)

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

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

答案 1 :(得分:9)

是的,有。你应该这样实现。

@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. 如果上述条件没有通过,只需按回到您的活动,以便处理它。
  3. 注意

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

    修改

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

    下载Fragment Back Stack申请。

答案 2 :(得分:5)

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

答案 3 :(得分:1)

您可以为片段实现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;
    }
} );

答案 4 :(得分:-10)

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