問題描述
我想制作一個對話片段
,詢問你確定嗎?"回復是/否".
I'd like to make a dialog fragment
that asks "Are you sure?" with a "yes/no" reply.
我查看了文檔,它真的很冗長,到處都是這個地方,解釋了如何制作高級對話框,但沒有完整的代碼來制作一個簡單的hello world"類型的對話框.大多數教程使用已棄用的對話框系統.官方博客似乎過于復雜且難以理解.
I've looked at the documentation and it's really verbose, going all over the place, explaining how to make advanced dialog boxes, but no intact code on making a simple 'hello world' kind of dialog box. Most tutorials utilize the deprecated dialog box system. The official blog seems to be unnecessarily complicated and difficult to understand.
那么,創建和顯示一個真正基本的警報對話框的最簡單方法是什么?使用支持庫的獎勵積分.
So, what's the simplest way to create and display a really basic Alert Dialog? Bonus points if it's using the support library.
推薦答案
DialogFragment 其實就是一個包裝了對話框的片段.您可以通過在 DialogFragment 的 onCreateDialog() 方法中創建并返回對話框來將任何類型的對話框放入其中.
A DialogFragment is really just a fragment that wraps a dialog. You can put any kind of dialog in there by creating and returning the dialog in the onCreateDialog() method of the DialogFragment.
這是一個示例 DialogFragment:
Heres an example DialogFragment:
class MyDialogFragment extends DialogFragment{
Context mContext;
public MyDialogFragment() {
mContext = getActivity();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setTitle("Really?");
alertDialogBuilder.setMessage("Are you sure?");
//null should be your on click listener
alertDialogBuilder.setPositiveButton("OK", null);
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
}
創建對話調用:
new MyDialogFragment().show(getFragmentManager(), "MyDialog");
并從某處關閉對話框:
((MyDialogFragment)getFragmentManager().findFragmentByTag("MyDialog")).getDialog().dismiss();
只需更改導入以使用支持庫類,所有這些代碼都將與支持庫完美配合.
All of that code will work perfectly with the support library, by just changing the imports to use the support library classes.
這篇關于最簡單的是/否對話框片段的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!