上一篇介紹了AlterDialog的基本用法,今天來介紹AlterDialog的延伸用法。
第一種是條列式的點選對話框
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button button;
String[] strings ={"第二天" , "第四天" , "第六天" , "第八天" , "第十天"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(MainActivity.this);
}
@Override
public void onClick(View view) {
getDialog();
}
private void getDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(false);
builder.setTitle("IT鐵人賽");
builder.setItems(strings, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
button.setText(strings[i]);
}
});
builder.create().show();
}
}
成果如下
第二種是選擇式對話框
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button button;
String[] strings ={"第二天" , "第四天" , "第六天" , "第八天" , "第十天"};
int index;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(MainActivity.this);
}
@Override
public void onClick(View view) {
getDialog();
}
private void getDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(false);
builder.setTitle("IT鐵人賽");
builder.setSingleChoiceItems(strings,0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
index = i;
}
});
builder.setPositiveButton("確定" , new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
button.setText(strings[index]);
dialogInterface.dismiss();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.create().show();
}
}