注销应用程序时如何禁用 Android 设备的返回按钮?


此示例展示了注销应用程序时如何禁用 Android 设备的返回按钮。

步骤 1 − 在 Android Studio 中创建一个新项目,转至文件 rArr; 新项目并填写所有所需信息以创建新项目。

步骤 2 − 将以下代码添加到 res/layout/activity_main.xml。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
   android:orientation="vertical"
   android:padding="16dp"
   android:gravity="center"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello World!"/>
</LinearLayout>

步骤 3 − 将以下代码添加到 src/MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   @Override
   public void onBackPressed() {
      Toast.makeText(getApplicationContext(), "Disabled Back Press", Toast.LENGTH_SHORT).show();
   }
}

步骤 4 − 将以下代码添加到 androidManifest.xml

<?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">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
   </activity>
</application>
</manifest>

让我们尝试运行你的应用程序。我假设你已将真正的 Android 移动设备与计算机连接。要从 Android Studio 运行应用程序,请打开项目的一个活动文件,然后单击工具栏中的运行 播放图标  图标。选择移动设备作为选项,然后检查将显示如下默认屏幕的移动设备 −

单击此处下载项目代码

更新日期: 2020 年 7 月 7 日

超过 1K 次浏览

开启您的职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.