Android使用DialogFragment

  • 内容
  • 评论
  • 相关

主程序文件

package com.example.mydialogfragment;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Fragment1 dialogFragment = Fragment1.newInstance("Are You Sure Want To Do This?");
		dialogFragment.show(getFragmentManager(), "dialog");
	}
	
	public void doPositiveClick(){
		Log.d("DialogFragmentExample", "User clicks on OK");
	}
	
	public void doNegativeClick(){
		Log.d("DialogFragmentExample", "User clicks on Cancel");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

Fragment1.java

package com.example.mydialogfragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;

public class Fragment1 extends DialogFragment {
	static Fragment1 newInstance(String title){
		Fragment1 fragment = new Fragment1();
		Bundle args = new Bundle();
		args.putString("title", title);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		String title = getArguments().getString("title");
		return new AlertDialog.Builder(getActivity()).setIcon(R.drawable.ic_launcher).setTitle("title").setPositiveButton("OK", new 
				DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						((MainActivity) getActivity()).doPositiveClick();
						
						
					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						((MainActivity) getActivity()).doNegativeClick();
					}
				}).create();
	}
}

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>

评论

0条评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注