android 如何在一个普通类的一个方法里面传递context参数?
本文介绍了android 如何在一个普通类的一个方法里面传递context参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
比如我想把有关数据库sqlite的操作放在一个公共的当中,` MySqliteHelper mySqliteHelper=new MySqliteHelper(); //这个方法的第一个参数需要传递一个context的值,也就是activity.class的对象,请问对于一个普通的类,这个应该怎么传递??求指导
解决方案
创建方法
public Helper(Context context)
{
this.context = context;
}
-------------分割线--------------
在工具类里直接获取applicationContext,这样可以避免每次调用都传入context
先自己定义一个application
public class MyApplication extends Application {
private static Context mContext;
@Override
public void onCreate(){
super.onCreate();
mContext = getApplicationContext();
}
public static Context getGlobalContext(){
return mContext;
}
}
然后在manifest中使用它
<application
android:name="包名路径.MyApplication"
android:allowBackup="true"
android:icon="@mipmap/app_icon"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
工具类中这样使用就可以了
private NetworkHelper(){
context = MyApplication.getGlobalContext();
}
这篇关于android 如何在一个普通类的一个方法里面传递context参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文