dialog弹出自定义窗体遇到的坑,dialog弹出版本信息

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/smallbabylong/article/details/79665876

使用dialog弹出自定义窗体

  • 第一步创建一个xml布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:id="@+id/dialog_about_infor"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="match_parent"
        android:text="每日一图"

        android:textSize="30dp"
        android:layout_height="40dp" />
<TextView

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/versionColor"
    android:text="@string/version"/>
    <TextView
        android:text="tips"
        android:gravity="center_horizontal"
        android:textColor="@color/tipsColor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
<TextView
    android:id="@+id/tips"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
    <Button
        android:id="@+id/check_update"
        android:textAlignment="center"
        android:background="@color/white"
        android:text="@string/check_update"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
  • 第二步编写代码函数
 public void showNoticeDialog(Context mContext) {
        // 构造对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        AlertDialog dialog = builder.create();
        View view = View.inflate(mContext, R.layout.dialog_about_infor, null);
        Button button=view.findViewById(R.id.check_update);
        TextView tips=view.findViewById(R.id.tips);
        tips.setText("测试测试手册!ヾ(=・ω・=)oヾ(=・ω・=)o");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this,"已是最新!(*/ω\*)",Toast.LENGTH_SHORT).show();
            }
        });
        dialog.setView(view,0,0,0,0);// 设置边距为0,保证在2.x的版本上运行没问题

        dialog.show();
    }

以上代码可以直接使用,过程中添加相应字符串变量即可

下面说一下遇到的坑

  • 使用dialog.setView()
    -出错 You need to use a Theme.AppCompat theme (or descendant) with this activity.
    原因是引入了v7的AlertDialog改为import android.app.AlertDialog;

    -错误: Unable to add window – token null is not for an application
    //虽然这里的参数是AlertDialog.Builder(Context context)但我们不能使用getApplicationContext()获得的Context,而必须使用Activity.this,因为只有一个Activity才能添加一个窗体。

猜你喜欢

转载自blog.csdn.net/smallbabylong/article/details/79665876