片段中的Android onBackPressed()

时间:2016-11-19 21:35:47

标签: java android android-fragments

我有一个片段,我必须实现onBackPressed()方法,但它不起作用

SELECT u.uri, k.score_x
FROM uris u JOIN
     (SELECT id, SUM(x) AS score_x
      FROM keywords
      WHERE k.key in ('key1', 'key2', 'key3', 'key4')
      GROUP BY id
      HAVING COUNT(DISTINCT key) = 4
     ) k
     ON u.id = k.id
ORDER BY k.score_sum DESC;

我有3种方法:

的onCreate:

public void onBackPressed(){
        new AlertDialog.Builder(getActivity())
          .setTitle(R.string.app_name)
          .setMessage("Are you sure you want to exit?")
          .setNegativeButton(android.R.string.no, null)
          .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() 
{

    public void onClick(DialogInterface arg0, int arg1) 
{
      ((MainActivity)PaymentFragment.this.getActivity()).showOrders();
}
        }).create().show();
}

onCreateView():

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

onActivityResult() - 我在这里转到PayPal活动

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    btnPayment = (Button) root.findViewById(R.id.btnPayPal);

    btnPayment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(SessionManager.totalPayment>0){
                PayPalPayment payment = new PayPalPayment(new BigDecimal(SessionManager.totalPayment), "EUR", "SSSSS",
                        PayPalPayment.PAYMENT_INTENT_SALE);

                Intent intent = new Intent(getActivity(), PaymentActivity.class);

                intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);

                startActivityForResult(intent, 0);
            }else{
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
                alertDialogBuilder.setTitle(R.string.app_name);
                alertDialogBuilder
                        .setMessage(R.string.empty_cart)
                        .setCancelable(true)
                        .setPositiveButton(R.string.ok,new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {

                            }
                        });
    return root;   //view
}

我想创建一个对话框,如果用户确认他要退出,则会转到showOrders Fragment。我应该在哪种方法中包含onBackPressed()方法,如何更改代码以用于片段?我已经阅读了有关StackOverflow的几篇文章,但它没有回答我的问题。谢谢!

1 个答案:

答案 0 :(得分:0)

fragment.getView().setFocusableInTouchMode(true);
fragment.getView().requestFocus();
fragment.getView().setOnKeyListener( new OnKeyListener() {
    @Override
    public boolean onKey( View v, int keyCode, KeyEvent event ){
        if( keyCode == KeyEvent.KEYCODE_BACK ) {
            return true;
        }
        return false;
    }
});