2016-08-09 31 views
0

我想提示用戶使用到退出該應用程序的上回壓,但我很努力在我的片段來實現這個退出應用程序對話

public class HomeFragment extends Fragment { 
 

 

 
    public HomeFragment() { 
 
     // Required empty public constructor 
 
    } 
 

 

 
    @Override 
 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
 
          Bundle savedInstanceState) { 
 
     // Inflate the layout for this fragment 
 
     return inflater.inflate(R.layout.fragment_home, container, false); 
 
    } 
 

 
    @Override 
 
    public void onBackPressed() { 
 
     new AlertDialog.Builder(this) 
 
       .setTitle("Really Exit?") 
 
       .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) { 
 
         HomeFragment.super.onBackPressed(); 
 
        } 
 
       }).create().show(); 
 
    } 
 
}

+2

我不認爲你可以從一個片段覆蓋onBackPressed(),你需要從包含片段的活動中做到這一點 – has19

+0

你可以在對話框中添加NegativeButton(Cancel),所以當用戶點擊取消按鈕,然後你可以解除對話。 –

+1

你不能在片段 – darwin

回答

1

你不能在碎片內部做到這一點,但在你的情況下可能會因爲每個碎片都在某個Activity上運行。

只需在包含片段的活動上放置onBackPressed代碼即可。

0

你能試試這個方法,並檢查是否正常工作:

@Override 
public void onDetach() { 
    super.onDetach(); 
    PUT YOUR CODE HERE 
} 
+0

似乎不起作用的片段 – james

1

使用此代碼顯示警告對話框

final android.support.v7.app.AlertDialog.Builder alertDialog = new android.support.v7.app.AlertDialog.Builder(getActivity()); 
     alertDialog.setTitle("Your text"); 
     alertDialog.setMessage("Your custom text") 
       .setCancelable(true).setPositiveButton("Rate Us", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialogInterface, int i) { 
       //your custom toast 
      } 
     }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialogInterface, int i) { 
       dialogInterface.cancel(); 
      } 
     }).create().show(); 

    }