在 Android 中如何显示 Toast?


本示例演示如何在 Android 中显示 Toast。

步骤 1 − 在 Android Studio 中创建一个新项目,转到 File rArr; New Project,并填写所有必需的信息来创建一个新项目。

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

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello World!"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

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

package com.example.sample;
import android.support.v7.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);
      //Displaying Toast with Hello World message
      Toast.makeText(getApplicationContext(),"Hello World",Toast.LENGTH_SHORT).show();
   }
}

步骤 4 − 将以下代码添加到 Manifests/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.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 运行应用程序,打开你的一个项目活动文件,并点击工具栏中的运行 Play Icon  图标。选择你的移动设备作为选项,然后查看你的移动设备,它将显示你的默认屏幕 −

单击 此处 下载项目代码

更新于: 03-Jul-2020

905 次浏览

开始您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.