替代alertdialog.builder.setview for API 21以下

时间:2015-10-06 20:38:06

标签: android android-layout datepicker android-alertdialog android-timepicker

我们知道alertdialog.builder.setview函数在API 21中引入,它允许我们设置布局。是否有任何替代方法来实现这一点,我也不想使用support library enter image description here

这就是我想要创造的东西

听到的是代码

这是datetime_dialog.xml个文件

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

    <DatePicker
        android:id="@+id/datePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:calendarViewShown="false" />

</LinearLayout>

java文件的代码

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
        MainActivity.this, AlertDialog.THEME_HOLO_DARK);
alertDialogBuilder.setView(R.layout.datetime_dialog);
alertDialogBuilder.setPositiveButton("Done",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // go to a new activity of the app
                Intent positveActivity = new Intent(
                        getApplicationContext(),
                        MainActivity.class);
                startActivity(positveActivity);
            }
        });
// set negative button: No message
alertDialogBuilder.setNegativeButton("Cancel",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // cancel the alert box and put a Toast to the
                // user
                dialog.cancel();

            }
        });

AlertDialog alertDialog = alertDialogBuilder.create();
// show alert
alertDialog.show();

我想支持这个API 9是否可能

1 个答案:

答案 0 :(得分:1)

首先需要从布局创建视图,其中包含:

View v = LayoutInflater.inflate(R.layout.ID, null);
AlertDialog.Builder ad = new AlertDialog.Builder(Activity);
ad.setview(v);