如何在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