オプションを選択しないと閉じられないダイアログを実装する方法2

3127 ワード

この方法では、ダイアログを開く後、選択項目がない場合はPositive Buttonを無効にし、オプションを選択するとPositive Buttonを使用可能にする.
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	private Button btnOpenDialog;
	private String[] books = null;
	private Activity activity;
	private int selectedBookIndex = -1;
	private AlertDialog alertDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initBooks();
		setContentView(R.layout.activity_main);
		activity = this;
		btnOpenDialog = (Button) findViewById(R.id.btnOpenDialog);
		btnOpenDialog.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog = new AlertDialog.Builder(activity).setTitle(R.string.hello_world).setSingleChoiceItems(books, selectedBookIndex, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						selectedBookIndex = which;
						allowCloseDialogByTapPositiveButton();
					}

				}).setNegativeButton(" ", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						selectedBookIndex = -1;
						// distoryDialog(dialog);
						return;
						
					}
				}).setPositiveButton(" ", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(selectedBookIndex == -1){
							alertDialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
							Toast.makeText(activity, " , , !", Toast.LENGTH_LONG).show();
							// keepDialog(dialog);
							return;
						}else{
							Toast.makeText(activity, " :" + books[selectedBookIndex] + ".", Toast.LENGTH_LONG).show();
						}
					}
				}).show();
				alertDialog.setCancelable(false);
				alertDialog.setCanceledOnTouchOutside(false);
				allowCloseDialogByTapPositiveButton();
				
			}
		});
	}
	
	private void allowCloseDialogByTapPositiveButton() {
        if(selectedBookIndex > -1) {
			alertDialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(true);
		}else{
			alertDialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
		}
    }

	void initBooks() {
		books = new String[] { " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " " };
	}
}