在Android開發中,我們經常會需要在Android界面上彈出一些對話框,比如詢問用戶或者讓用戶選擇。這些功能我們叫它Android Dialog對話框,AlertDialog實現方法為建造者模式。下面我們簡單模擬一個挑媳婦的選擇確定對話框(單選)對話框,不同於示例二之處在於本次只要不確定就可以後悔哦,如下圖:
Layout界面代碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="單向選擇"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="show3"
android:id="@+id/button3" />
</LinearLayout>
Java功能實現代碼:
public class AlertDialogDemo extends AppCompatActivity {
int index=0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alertdialog);
}
public void show3(View v){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("挑媳婦兒");
final String[] beautifulGirls = {"芙蓉姐姐","鳳姐","范爺","我自己"};
builder.setSingleChoiceItems(beautifulGirls, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
index = which;
}
});
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(AlertDialogDemo.this,beautifulGirls[index]+"是你的媳婦了",Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
}
優化空間很大,大家都可以玩玩。