android單項列表

1、activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="單項列表選擇框" />

</LinearLayout>

2、MainActivity.java

import android.app.Activity;
import android.app.AlertDialog;
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 btn1;
	//	用來保存選擇的元素ID
	int nSingleChoiceID = -1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		final String[] nItems = {"item1","item2","item3", "item4", "item5", "item6"};
	
		
		btn1 = (Button) findViewById(R.id.button1);
		btn1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
				
				builder.setIcon(R.drawable.ic_launcher);
				builder.setTitle("單項選擇");
				builder.setSingleChoiceItems(nItems, 0, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						nSingleChoiceID = arg1;
						//	顯示提示信息
						String strTip = "你選擇的Id爲" + arg1 + ",值爲" + nItems[arg1];
						Toast toast = Toast.makeText(getApplicationContext(), strTip, Toast.LENGTH_SHORT);
						toast.show();
					}
				});
				builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						if (nSingleChoiceID > -1) {
							Toast toast = Toast.makeText(getApplicationContext(), "你選擇的是"+nItems[nSingleChoiceID], Toast.LENGTH_SHORT);
							toast.show();							
						}
					}
				});
				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						
					}
				});
				
				builder.create().show();
			}
		});
	}
}

3、效果圖

效果圖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章