如何在Android中使用單例類?
在進入示例之前,我們應該瞭解什麼是單例設計模式。單例是一種設計模式,它限制類的例項化只產生一個例項。值得注意的用途包括控制併發和建立應用程式訪問其資料儲存的中心訪問點。
此示例演示如何在Android中使用單例類
步驟 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:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <EditText android:id = "@+id/editText" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:hint = "Enter text" /> <Button android:id = "@+id/save" android:text = "save in singleTone" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout>
在上面的程式碼中,我們使用了 EditText 和 Button。當用戶單擊按鈕時,它將從 EditText 獲取資料並將其儲存在單例類中,然後在 Toast 中顯示單例類中的值。
步驟 3 − 將以下程式碼新增到 src/MainActivity.java
package com.example.andy.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editText;
Button save;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
save = findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(editText.getText().toString().isEmpty()) {
editText.setError("Enter text");
}else{
String editValue = editText.getText().toString();
singleTonExample singletonexample = com.example.andy.myapplication.singleTonExample.getInstance();
singletonexample.setText(editValue);
Toast.makeText(MainActivity.this,singletonexample.getText(),Toast.LENGTH_LONG).show();
}
}
});
}
}在上面的程式碼中,我們使用了 singleTonExample 作為單例類,因此建立一個名為 singleTonExample.java 的類並新增以下程式碼:
package com.example.andy.myapplication;
import java.security.Identity;
public class singleTonExample {
String editValue;
private static final singleTonExample ourInstance = new singleTonExample();
public static singleTonExample getInstance() {
return ourInstance;
}
private singleTonExample() { }
public void setText(String editValue) {
this.editValue = editValue;
}
public String getText() {
return editValue;
}
}讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要在 Android Studio 中執行應用程式,請開啟專案中的一個 activity 檔案,然後單擊工具欄中的執行
圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 –

在上面的結果中,我們寫的是“tutorialspoint.com”,現在單擊按鈕,它將從單例類獲取資料,並在 Toast 中顯示如下所示:

點選 這裡 下載專案程式碼
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP