Android dialog Single Choice Items


เตรียมปุ่มไว้ใน layout/main.xml หน่อยก่อน

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
	<Button 
	android:layout_width="wrap_content" 
	android:id="@+id/show_dialog_btn"
	android:layout_height="wrap_content" 
	android:text="@string/show_dialog" />
</LinearLayout>

เขียน code มาเรียกใช้มัน

public class DialogDemo extends Activity 
                        implements OnClickListener
                        {
    private static final String TAG = "DialogDemo";
    private Button showDialogButton;
    private Context mContext; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "Activity start");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mContext = this; // to use all around this class
        initView();
        initViewAction();
       
    }

    private void initView() {
         showDialogButton = 
             (Button) findViewById(R.id.show_dialog_btn);
    }
    
    private void initViewAction() {
        showDialogButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        
        if (view.equals(showDialogButton)) {
            showDialogButtonClick();
        }
    }

    private void showDialogButtonClick() {
        Log.i(TAG, "show Dialog ButtonClick");
        AlertDialog.Builder builder = 
            new AlertDialog.Builder(mContext);
        builder.setTitle("Show dialog");
        
        final CharSequence[] choiceList = 
        {"Coke", "Pepsi" , "Sprite" , "Seven Up" };
        
        int selected = -1; // does not select anything
        
        
        builder.setSingleChoiceItems(
                choiceList, 
                selected, 
                new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(
                    DialogInterface dialog, 
                    int which) {
                Toast.makeText(
                        mContext, 
                        "Select "+choiceList[which], 
                        Toast.LENGTH_SHORT
                        )
                        .show();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }
}

ผล

แบบให้มีเลือกไว้ก่อน 1 ตัว(เริ่มที่ 0)

private void showDialogButtonClick() {
        Log.i(TAG, "show Dialog ButtonClick");
        AlertDialog.Builder builder = 
            new AlertDialog.Builder(mContext);
        builder.setTitle("Show dialog");
        
        final CharSequence[] choiceList = 
        {"Coke", "Pepsi" , "Sprite" , "Seven Up" };
        
        int selected = 0; // select at 0
        
        
        builder.setSingleChoiceItems(
                choiceList, 
                selected, 
                new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(
                    DialogInterface dialog, 
                    int which) {
                Toast.makeText(
                        mContext, 
                        "Select "+choiceList[which], 
                        Toast.LENGTH_SHORT
                        )
                        .show();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }

ผล

แบบมีปุ่มยืนยัน

    private int selected = 0; // change selected to global 
    private void showDialogButtonClick() {
        Log.i(TAG, "show Dialog ButtonClick");
        AlertDialog.Builder builder = 
            new AlertDialog.Builder(mContext);
        builder.setTitle("Show dialog");
        
        final CharSequence[] choiceList = 
        {"Coke", "Pepsi" , "Sprite" , "Seven Up" };
 
        builder.setSingleChoiceItems(
                choiceList, 
                selected, 
                new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(
                    DialogInterface dialog, 
                    int which) {
                selected = which;
            }
        })
        .setCancelable(false)
        .setPositiveButton("โอเค", 
        	new DialogInterface.OnClickListener() 
        	{
				@Override
				public void onClick(DialogInterface dialog, 
						int which) {
					//not the same as 'which' above
					Log.d(TAG,"Which value="+which);
					Log.d(TAG,"Selected value="+selected);
					Toast.makeText(
	                        mContext, 
	                        "Select "+choiceList[selected], 
	                        Toast.LENGTH_SHORT
	                        )
	                        .show();
				}
        	});
        
        AlertDialog alert = builder.create();
        alert.show();
    }

ผล

มี ok, cancel

    private int selected = 0; 
    private int buffKey = 0; // add buffer value 
    private void showDialogButtonClick() {
        Log.i(TAG, "show Dialog ButtonClick");
        AlertDialog.Builder builder = 
            new AlertDialog.Builder(mContext);
        builder.setTitle("Show dialog");
        
        final CharSequence[] choiceList = 
        {"Coke", "Pepsi" , "Sprite" , "Seven Up" };
       
        builder.setSingleChoiceItems(
                choiceList, 
                selected, 
                new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(
                    DialogInterface dialog, 
                    int which) {
            	//set to buffKey instead of selected 
            	//(when cancel not save to selected)
            	buffKey = which;
            }
        })
        .setCancelable(false)
        .setPositiveButton("โอเค", 
        	new DialogInterface.OnClickListener() 
        	{
				@Override
				public void onClick(DialogInterface dialog, 
						int which) {
					Log.d(TAG,"Which value="+which);
					Log.d(TAG,"Selected value="+buffKey);
					Toast.makeText(
	                        mContext, 
	                        "Select "+choiceList[buffKey], 
	                        Toast.LENGTH_SHORT
	                        )
	                        .show();
					//set buff to selected
					selected = buffKey;
				}
        	}
        )
        .setNegativeButton("ไม่โอเค", 
        	new DialogInterface.OnClickListener() 
	    	{
				@Override
				public void onClick(DialogInterface dialog, 
						int which) {
					Toast.makeText(
	                        mContext, 
	                        "Cancel click", 
	                        Toast.LENGTH_SHORT
	                        )
	                        .show();
				}
	    	}
        );
        
        AlertDialog alert = builder.create();
        alert.show();
    }

ผล

latest version of code http://paste2.org/p/1408322

Advertisements

22 thoughts on “Android dialog Single Choice Items

  1. Your examples are better than Google’s Android API demo’s on this topic. I made a link to your examples in a StackOverflow.com question (4719051). I think others will benefit from your clear, easy-to-use examples. They helped me:-)

    Thank you!

  2. I want to have the list of choices… but NO ok/cancel buttons.
    (I did it!)

    I want to detect when the user picks a choice.
    (I did it!)

    I want to detect when the user just hits BACK without picking a choice.
    (Can’t figure that 1 out.)

    Help!

  3. Nice article but little bit more helpful code as follow just add one thing in your code witch is useful to dismiss current dialog after select any item.

    ——————————————————————————————-
    public class DialogDemo extends Activity implements OnClickListener{
    private static final String TAG = “DialogDemo”;
    private Button showDialogButton;
    private Context mContext;
    private AlertDialog alert;
    private int selected = -1;// does not select anything

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    Log.i(TAG, “Activity start”);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mContext = this; // to use all around this class
    initView();
    initViewAction();

    }

    private void initView() {
    showDialogButton = (Button) findViewById(R.id.show_dialog_btn);
    }

    private void initViewAction() {
    showDialogButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

    if (view.equals(showDialogButton)) {
    showDialogButtonClick();
    }
    }

    private void showDialogButtonClick() {
    Log.i(TAG, “show Dialog ButtonClick”);
    AlertDialog.Builder builder =new AlertDialog.Builder(mContext);
    builder.setTitle(“Show dialog”);

    final CharSequence[] choiceList = {“Coke”, “Pepsi” , “Sprite” , “Seven Up” };

    builder.setSingleChoiceItems(choiceList,selected,newDialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog,int which) {
    Toast.makeText(mContext,”Select “+choiceList[which],Toast.LENGTH_SHORT
    ).show();
    alert.dismiss();
    }
    });
    alert = builder.create();
    alert.show();
    }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s