How to show alert dialog in Android?
本示例演示了如何在android中显示警报对话框。
步骤1 ? 在Android Studio中创建一个新项目,转到文件? 新建项目,并填写所有必需的详细信息以创建一个新项目。
第2步 ? 将以下代码添加到res / layout / activity_main.xml。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Press The Back Button." android:textStyle="bold" android:textSize="24sp" android:layout_centerInParent="true" /> </RelativeLayout> |
第3步? 将以下代码添加到src / MainActivity.java中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import android.app.AlertDialog; import android.content.DialogInterface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public void onBackPressed() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage("Do you want to exit?"); builder.setTitle("Alert!"); builder.setCancelable(false); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } } |
步骤4-将以下代码添加到androidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <intent-filter> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
让我们尝试运行您的应用程序。 我假设您已将实际的Android Mobile设备与计算机连接。 要从android studio运行该应用,请打开您项目的活动文件之一,然后从工具栏中单击运行 icon。 选择您的移动设备作为选项,然后检查将显示默认屏幕的移动设备–
单击此处下载项目代码。