如何自定义android对话框到材质主题?

时间:2016-06-30 12:39:52

标签: android android-layout android-dialogfragment android-dialog

我想自定义android对话框,使其看起来像下面的浮动对话框,建议在https://material.google.com/components/dialogs.html#dialogs-simple-dialogs enter image description here

我尝试创建一个DialogFragment,其中onCreateDialog返回一个Dialog,其视图的根目录是CardView.But无法获得预期的结果。我可以就如何实现这一点提出一些建议吗?

我的布局看起来像这样,



<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center|top"
    card_view:cardElevation="5dp"
    card_view:cardPreventCornerOverlap="false">
  //Contents come here
  
</android.support.v7.widget.CardView>
&#13;
&#13;
&#13;

并在代码中

public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = new Dialog(getActivity());
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_font_selection,null,false);

        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(view);
        float width = (I am getting screen width here) * .80f;
        dialog.getWindow().setLayout((int) width, ViewGroup.LayoutParams.WRAP_CONTENT);
        return dialog;
    }`

但结果如下所示, 而不是升高,我得到一个黑色的阴影 enter image description here

2 个答案:

答案 0 :(得分:0)

AlertDialog.Builder mydialog = new AlertDialog.Builder( context);
mydialog.setTitle("Set backup accounts");
mydialog.setItems(CharSequence[] items, OnClickListener);
mydialog.show();
mydialog.setContentView(R.layout.mydialogLayout);

这在您的活动/片段中。所以声明你的布局如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal">

  <TextView
      android:id="@+id/myID1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
  <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
  <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />

</RelativeLayout>

之后,如果您想要处理点击,请执行以下操作:

TextView myView1 = (TextView) mydialog.findViewById(myID1);
myView1.setOnClickListener(...);

答案 1 :(得分:0)

MaterialAlertDialogBuilder现在可用于Android:

material.io/develop/android/components/dialog