今天介紹一下單選的列表 透過簡單的程式碼就可以做出一個清晰易懂的選擇表單
那就馬上附上我的程式碼~
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog();
}
});
}
private void dialog(){
final String choose[]={"A","B","C","D","以上皆是"};//創一個字串的陣列 要把它塞到dialog裡面
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("單選題"); //設置它的標題
builder.setSingleChoiceItems(choose,0,new DialogInterface.OnClickListener() {
//把它設置為單選的型態
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, "選擇了"+choose[i], Toast.LENGTH_SHORT).show();
//提醒使用者點選了選項
}
});
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show(); //也是一樣記得創建他並顯示
}
}
就能做出這樣子的dialog囉