简体   繁体   English

在这种情况下我应该使用什么类型的上下文,为什么?

[英]What type of context should I use in this case and why?

I am using the following function in one of my activities of my app:我在我的应用程序的一项活动中使用以下 function:

public static float convertDpToPixel(float dp, Context context){
    return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}

What context should I use?我应该使用什么上下文?

Application Context : tied to the Lifecycle of an Application应用程序上下文:与应用程序的生命周期相关

Activity Context : tied to the life cycle of activity活动上下文:与活动的生命周期相关

Base Context : the base context as set by the constructor or setBaseContext基础上下文:由构造函数或 setBaseContext 设置的基础上下文

I have done it like this and it seems to work:我是这样做的,它似乎有效:

In my_activity.java:在 my_activity.java 中:

float conversion = convertDpToPixel(10, this);

But also I could do the following:但我也可以做到以下几点:

float conversion = convertDpToPixel(10, getApplicationContext());

And also the following:还有以下内容:

float conversion = convertDpToPixel(10, getBaseContext());

I think that in this specific case it doesn't really matter as it will get the resources of the app and it is included in all the contextes types but I would like to ensure what I am saying.我认为在这种特定情况下,它并不重要,因为它将获得应用程序的资源,并且它包含在所有上下文类型中,但我想确保我在说什么。 Thanks谢谢

All of three you can use in this case.在这种情况下,您可以使用所有这三个。 Context usually use to get resource or launch some system service, and I found a context explain in this website https://www.jianshu.com/p/94e0f9ab3f1d , here is the picture he explain when each context can be use: (不推荐 mean not recommended) context通常用于获取资源或启动一些系统服务,我在这个网站https://www.jianshu.com/p/94e0f9ab3f1d找到了context的解释,这里是他解释每个context可以使用的图片:(不推荐表示不推荐) 在此处输入图像描述

Most of case you can use Application, Activity, and Service context, but beside some scene, like show dialog,start activity, and layout inflation.大多数情况下,您可以使用应用程序、活动和服务上下文,但在某些场景旁边,如显示对话框、启动活动和布局膨胀。 A dialog need to build base on a activity, so you can't use other two type context.对话需要建立在活动的基础上,因此您不能使用其他两种类型的上下文。 This case seems to be load resource values, so you can use all of three.这种情况似乎是加载资源值,因此您可以同时使用这三个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM