1. 程式人生 > 程式設計 >android實現彈出提示框

android實現彈出提示框

本文例項為大家分享了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("是",int which) {//確定按鈕的響應事件

       }
      }).setNegativeButton("否",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佈局顯示,再比如定義多個選擇按鈕什麼的,這些大家可以自行學習。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。