要在安卓中宣告全域性變數,該怎麼辦?


本例演示如何在安卓中宣告全域性變數?

步驟 1 − 在 Android Studio 中新建一個專案,轉到檔案 ⇒ 新建專案並填寫所有必需的資訊以新建一個專案。

步驟 2 − 向 res/layout/activity_main.xml 中新增以下程式碼。

<?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:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:orientation = "vertical">
   <TextView
      android:id = "@+id/actionEvent"
      android:textSize = "40sp"
      android:layout_marginTop = "30dp"
      android:layout_width = "wrap_content"
      android:layout_height = "match_parent" />
</LinearLayout>

在上述程式碼中,我們取文字檢視以顯示全域性變數。

步驟 3 − 向 src/MainActivity.java 中新增以下程式碼

package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   TextView actionEvent;
   @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      actionEvent = findViewById(R.id.actionEvent);
      actionEvent.setText("Click");
      actionEvent.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            singleToneClass singleToneClass = com.example.myapplication.singleToneClass.getInstance();
            singleToneClass.setData("Tutorialspoint.com");
            actionEvent.setText(singleToneClass.getData());
         }
      });
   }
}

步驟 4 − 向 src/singleToneClass.java 中新增以下程式碼

package com.example.myapplication;
public class singleToneClass {
   String s;
   private static final singleToneClass ourInstance = new singleToneClass();
   public static singleToneClass getInstance() {
      return ourInstance;
   }
   private singleToneClass() {
   }
   public void setData(String s) {
      this.s = s;
   }
   public String getData() {
      return s;
   }
}

讓我們嘗試執行您的應用程式。我假定您已經將您的安卓手機裝置與您的計算機連線。要從安卓工作室執行該應用,開啟您的一個專案活動檔案並點選工具欄中的執行  圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 –

現在點選文字檢視,它將顯示如下所示的結果 –

點選 此處 下載專案程式碼

更新於:2019 年 7 月 30 日

5K+ 瀏覽次數

開啟你的 職業生涯

完成課程並獲取認證

開始學習
廣告
© . All rights reserved.