android实现弹出提示框

2021-01-21 0 693

本文实例为大家分享了anadroid实现弹出提示框的具体代码,供大家参考,具体内容如下

提示框是利用AlertDialog实现的。

代码:

(设置在button的点击事件中)

 new AlertDialog.Builder(MainActivity.this).setTitle(\"信息提示\")//设置对话框标题

      .setMessage(\"是否需要更换xxx?\")
      .setPositiveButton(\"是\", new DialogInterface.OnClickListener() {//添加确定按钮

       @Override
       public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件,点击事件没写,自己添加

       }
      }).setNegativeButton(\"否\", new DialogInterface.OnClickListener() {//添加返回按钮

     @Override
     public void onClick(DialogInterface dialog, int which) {//响应事件,点击事件没写,自己添加

     }

    }).show();//在按键响应事件中显示此对话框
   }
 });

实现效果:

android实现弹出提示框

完整代码:

package com.example.myapplicationusealertdialog;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
 Button bnt;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  bnt = findViewById(R.id.button);
  bnt.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    new AlertDialog.Builder(MainActivity.this).setTitle(\"信息提示\")//设置对话框标题

      .setMessage(\"是否需要更换xxx?\")
      .setPositiveButton(\"是\", new DialogInterface.OnClickListener() {//添加确定按钮

       @Override
       public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件

       }
      }).setNegativeButton(\"否\", new DialogInterface.OnClickListener() {//添加返回按钮

     @Override
     public void onClick(DialogInterface dialog, int which) {//响应事件

     }

    }).show();//在按键响应事件中显示此对话框
   }
  });
 }
}
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"
 xmlns:app=\"http://schemas.android.com/apk/res-auto\"
 xmlns:tools=\"http://schemas.android.com/tools\"
 android:layout_width=\"match_parent\"
 android:layout_height=\"match_parent\"
 tools:context=\".MainActivity\">

 <Button
  android:layout_width=\"200dp\"
  android:layout_marginLeft=\"100dp\"
  android:layout_height=\"wrap_content\"
  android:text=\"点击\"
  android:id=\"@+id/button\"/>

</LinearLayout>

其实AlertDialog可以添加其他的功能选项,比如在提示框里面绑定xml布局显示,再比如定义多个选择按钮什么的,这些大家可以自行学习。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

遇见资源网 Android android实现弹出提示框 http://www.ox520.com/23879.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务