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

使用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才能添加一个窗体。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林深人不知

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值