我在从静态方法调用非静态方法时面临一个大问题。
这是我的代码
Class SMS
{
public static void First_function()
{
SMS sms = new SMS();
sms.Second_function();
}
public void Second_function()
{
Toast.makeText(getApplicationContext(),"Hello",1).show(); // This i anable to display and cause crash
CallingCustomBaseAdapters(); //this was the adapter class and i anable to call this also
}
我可以调用 Second_function 但无法获取 Toast 和 CallCustomBaseAdapter() 方法,发生崩溃。
我应该怎么做才能解决这个问题?
public static void First_function(Context context)
{
SMS sms = new SMS();
sms.Second_function(context);
}
public void Second_function(Context context)
{
Toast.makeText(context,"Hello",1).show(); // This i anable to display and cause crash
}
实现此目的的唯一解决方案是您需要将当前上下文作为参数传递。
我只为Toast编写了代码,但您需要根据您的要求修改它。
从您的活动传递上下文First_function(getApplicationContext())
etc..
对于静态字符串
public static String staticString = "xyz";
public static String getStaticString()
{
return staticString;
}
String xyz = getStaticString();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)