【问题标题】:My new class isn't recognized into activity我的新课程未被识别为活动
【发布时间】:2020-01-29 08:39:25
【问题描述】:

我想将我所有的对话框移到一个类中并从那里访问。所以我创建了一个新的java类:

package com.myapp.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import androidx.appcompat.app.AlertDialog;
import com.myapp.R;

public class dialogs {

  public void showNetworkDialog (Context mContext) {
    AlertDialog.Builder builder =
            new AlertDialog.Builder(mContext, R.style.MyAlertDialogStyle);
    builder.setTitle(R.string.warning)
            .setCancelable(false)
            .setMessage(R.string.no_network)
            .setNegativeButton(R.string.quit, (dialog, id) ->  ((Activity)mContext).finish())
            .setPositiveButton(R.string.agree, (dialog, id) -> {
                Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
                mContext.startActivity(intent);
            }).show();
  }

}

我将新课程导入到我的活动中

import com.myapp.utils.dialogs;

问题是当我尝试访问时,我的 Android Studio 无法识别 showNetworkDialog 过程

showNetworkDialog(myActivity.this);

我做错了什么?

【问题讨论】:

标签: android class


【解决方案1】:

您必须创建dialogs 类的实例,然后尝试使用instance 调用此classmethod。喜欢以下。

dialogs dialog = new dialogs() 
dialog.showNetworkDialog(myActivity.this);

您可以创建static function 以避免创建instances,如下所示。

 public static void showNetworkDialog (Context mContext) {
   //....
  }

现在您可以使用class name 调用您的method,而无需创建instance

dialogs.showNetworkDialog(myActivity.this);

另一种方法

您可以创建一个单例类restrict 一个类的instantiation 到一个object

// singleton design pattern 
public class Dialogs { 
    private static Dialogs obj; 

   //make the constructor private so that this class cannot be instantiated
    private Dialogs() {} 

    // Only one thread can execute this at a time 
    public static synchronized Dialogs getInstance() { 
        if (obj==null) 
            obj = new Dialogs(); 
        return obj; 
    } 

    public void showNetworkDialog (Context mContext) {
      // your code here
    }
} 

现在您可以从任何地方调用您的方法,如下所示。

Dialogs.getInstance().showNetworkDialog(this);

【讨论】:

  • 我不确定单例是否一定比这里的静态方法好
  • 我觉得singleton更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
  • 2013-11-30
  • 2015-05-14
  • 1970-01-01
  • 2017-11-02
  • 2023-03-13
  • 1970-01-01
相关资源
最近更新 更多