DialogFragment以及AlertDialogFragment

傲慢的上校發表於2012-07-26

          作為一個拖延症嚴重型別的病人,終於開始這篇文章了,如果看到這篇文章的朋友,誰有對付拖延症的好的方法,謝謝推薦一下。程式碼部分昨天完成,其實是在上一週,在Activity(4.0開發環境下,Fragment學習資料:android之Fragment(官網資料翻譯))使用AlertDialog,被告知說showDialog(int id)這個方法Deprecated。被棄用了,建議使用DialogFragment。


         就開始dialogFragment的學習吧,先看下說明:

         A fragment that displays a dialog window, floating on top of its activity's window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.

         一個顯示一個對話方塊視窗的Fragment,漂浮在其Activity顯示視窗的頂部。這個Fragment包含一個對話方塊物件,它將基於Fragment的狀態適當的選擇顯示。應該通過API來控制Dialog(決定何時顯示、隱藏、銷燬),而不是直接呼叫Dialog。

        Implementations should override this class and implement onCreateView(LayoutInflater, ViewGroup, Bundle) to supply the content of the dialog. Alternatively, they can override onCreateDialog(Bundle) to create an entirely custom dialog, such as an AlertDialog, with its own content.

        實現DialogFragment是通過繼承DialogFragment並且實現 onCreateView(LayoutInflater, ViewGroup, Bundle) 這個方法來提供對話方塊內容。或者也可以重寫 onCreateDialog(Bundle)這個方法來建立一個自定義的對話方塊,像AlertDialog,有它自己的內容。

       下面開始一個簡單的例子:

        主Activity:

public class DialogFragmentDemoActivity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
	private Button mDialogButton;
	private Button mAlertDialogButton;
	private int mStackLevel;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mDialogButton = (Button)findViewById(R.id.dialog_button);
        mAlertDialogButton = (Button)findViewById(R.id.alert_dialog_button);
        mDialogButton.setOnClickListener(this);
        mAlertDialogButton.setOnClickListener(this);
    }
	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.dialog_button:
			showDialog();
			break;
		case R.id.alert_dialog_button:
			showAlertDialog();
			break;
		}
		
	}
	
	void showDialog() {
	    mStackLevel++;

	    // DialogFragment.show() will take care of adding the fragment
	    // in a transaction.  We also want to remove any currently showing
	    // dialog, so make our own transaction and take care of that here.
	    FragmentTransaction ft = getFragmentManager().beginTransaction();
	    Fragment prev = getFragmentManager().findFragmentByTag("dialog");
	    if (prev != null) {
	        ft.remove(prev);
	    }
	    ft.addToBackStack(null);

	    // Create and show the dialog.
	    DialogFragment newFragment = MyDialogFragment.newInstance(mStackLevel);
	    newFragment.show(ft, "dialog");
	}
	
	void showAlertDialog() {
	    DialogFragment newFragment = MyAlertDialogFragment.newInstance(
	            R.string.alert_dialog_button);
	    newFragment.show(getFragmentManager(), "dialog");
	}

	public void doPositiveClick() {
	    // Do stuff here.
	    Log.i("FragmentAlertDialog", "Positive click!");
	}

	public void doNegativeClick() {
	    // Do stuff here.
	    Log.i("FragmentAlertDialog", "Negative click!");
	}
		
}

主要看下showDialog的註釋說明: DialogFragment.show() will take care of adding the fragment in a transaction.  We also want to remove any currently showing dialog, so make our own transaction and take care of that here.

        DialogFragment.show()會管理新增到事務裡面的Fragment。在這裡,我們想要刪除當前顯示的對話方塊,就必須用自己的事務進行Fragment管理。

       看下MyDialogFragment和MyAlertDialogFragment的定義:

public class MyDialogFragment extends DialogFragment {
	int mNum;

    /**
     * Create a new instance of MyDialogFragment, providing "num"
     * as an argument.
     */
    static MyDialogFragment newInstance(int num) {
        MyDialogFragment f = new MyDialogFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments().getInt("num");

        // Pick a style based on the num.
        int style = DialogFragment.STYLE_NORMAL, theme = 0;
        switch ((mNum-1)%6) {
            case 1: style = DialogFragment.STYLE_NO_TITLE; break;
            case 2: style = DialogFragment.STYLE_NO_FRAME; break;
            case 3: style = DialogFragment.STYLE_NO_INPUT; break;
            case 4: style = DialogFragment.STYLE_NORMAL; break;
            case 5: style = DialogFragment.STYLE_NORMAL; break;
            case 6: style = DialogFragment.STYLE_NO_TITLE; break;
            case 7: style = DialogFragment.STYLE_NO_FRAME; break;
            case 8: style = DialogFragment.STYLE_NORMAL; break;
        }
        switch ((mNum-1)%6) {
            case 4: theme = android.R.style.Theme_Holo; break;
            case 5: theme = android.R.style.Theme_Holo_Light_Dialog; break;
            case 6: theme = android.R.style.Theme_Holo_Light; break;
            case 7: theme = android.R.style.Theme_Holo_Light_Panel; break;
            case 8: theme = android.R.style.Theme_Holo_Light; break;
        }
        setStyle(style, theme);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_dialog, container, false);
        View tv = v.findViewById(R.id.text);
        ((TextView)tv).setText("Dialog #" + mNum + ": using style "
                + "getNameForNum(mNum)");

        // Watch for button clicks.
        Button button = (Button)v.findViewById(R.id.dialog_show);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // When button is clicked, call up to owning activity.
                ((DialogFragmentDemoActivity)getActivity()).showDialog();
            }
        });

        return v;
    }
}

在onCreate()方法裡面通過num引數來設定DialogFragment的格式,看一下setArgument()這個方法:

Supply the construction arguments for this fragment.

為Fragment提供構造引數。

setStyle()方法:

Call to customize the basic appearance and behavior of the fragment's dialog. This can be used for some common dialog behaviors, taking care of selecting flags, theme, and other options for you. The same effect can be achieve by manually setting Dialog and Window attributes yourself. Calling this after the fragment's Dialog is created will have no effect.

Parameters
styleSelects a standard style: may be STYLE_NORMALSTYLE_NO_TITLESTYLE_NO_FRAME, or STYLE_NO_INPUT.
themeOptional custom theme. If 0, an appropriate theme (based on the style) will be selected for you.

在自定義Fragment對話方塊的外觀和行為時呼叫,通常被用於設定一些常見對話方塊的行為,像選擇Flag、主題以及其他。同樣你也可以通過手動選擇來設定對話方塊的屬性,但是在Fragment的Dialog建立以後,呼叫該方法無效。

       傲慢的上校原創作品,轉載請說明出處:http://blog.csdn.net/aomandeshangxiao/article/details/7790520

        再看MyAlertDialogFragment:

public class MyAlertDialogFragment extends DialogFragment {

	public static MyAlertDialogFragment newInstance(int title) {
		MyAlertDialogFragment frag = new MyAlertDialogFragment();
        Bundle args = new Bundle();
        args.putInt("title", title);
        frag.setArguments(args);
        return frag;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        int title = getArguments().getInt("title");

        return new AlertDialog.Builder(getActivity())
//                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(title)
                .setPositiveButton(R.string.alert_dialog_ok,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            ((DialogFragmentDemoActivity)getActivity()).doPositiveClick();
                        }
                    }
                )
                .setNegativeButton(R.string.alert_dialog_cancel,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            ((DialogFragmentDemoActivity) getActivity()).doNegativeClick();
                        }
                    }
                )
                .create();
    }
}

比較簡單,在onCreateDialog裡面返回一個自定義的dialog。

       找了近一個周的工作,也非常感謝CSDN上面好友們的幫助,現在工作不太好找,請換工作朋友三思。

最後,檔案下載地址:http://download.csdn.net/detail/aomandeshangxiao/4456176


       大體寫道如此,做飯吃飯去了。。。



相關文章