为什么我不能从另一个包含 Toast 的类调用静态方法? [英] Why can't I call a Static method from another class which contains a Toast?

查看:39
本文介绍了为什么我不能从另一个包含 Toast 的类调用静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在发布这篇文章之前,我做了我的研究,但我很难理解到底是什么问题.所以这是我在第 1 课中的方法:

Before posting this I did my research, but I am struggling to understand exactly what the issue is. So here is my method in class 1:

public static void scan() {
    for( int j=0; j< objarray.size();j++)
    {

        locationB.setLatitude(objarray.get(j).getlat());
        locationB.setLongitude(objarray.get(j).getlon());

        float distance = locationA.distanceTo(locationB);

        if((distance < 600)&&(distance > 0.0) )
        {
            Toast.makeText(getApplicationContext(),"You can go to" +objarray.get(j).gettitle(),Toast.LENGTH_SHORT).show(); 

        }

    }

这个方法中的一切都是静态的,唯一给我一个错误的是 Toast.makeText 调用.我是否需要将某些内容传递给包含 scan 方法的 class1?

Everything in this method is Static, and the only thing giving me an error is the Toast.makeText call. Do I need to pass something to class1 which contains the scan method?

像这样:

Class1.Scan(something);

我认为这可能与 Toast 中的 getApplicationContext() 有关,但我不确定我需要做什么才能解决这个问题.任何解释表示赞赏!

I think this may have something to do with the getApplicationContext() within the Toast, but I am unsure exactly what I need to do in order to fix this problem. Any explanation is appreciated!

推荐答案

我是否需要将某些内容传递给包含 scan 方法的 class1?

Do I need to pass something to class1 which contains the scan method?

是的,您需要将当前 Activity 上下文传递给 Scan 方法以显示 Toast 而不是直接调用 Class1 中的 getApplicationContext() 方法(来自非活动类).将扫描方法更改为:

Yes, you will need to pass current Activity context to Scan method for showing Toast instead of calling directly getApplicationContext() method in Class1 (from non Activity class). change Scan method as :

public static void Scan(Context context) {
   //...your code here....
    Toast.makeText(context,"You can go to"  
                  +objarray.get(j).gettitle(),Toast.LENGTH_SHORT).show(); 

    }

这篇关于为什么我不能从另一个包含 Toast 的类调用静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆