使用 Context 启动另一个 Activity [英] Use of Context to start another Activity

查看:29
本文介绍了使用 Context 启动另一个 Activity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要启动 Activity,您需要一个 Intent,例如:

To start an Activity you need an Intent, like:

Intent i = new Intent(context, class)

所以要填写上下文参数,有几个选项可用:

So to fill in the context parameter, a couple of options are available:

  • 使用 MyActivity.this 或仅使用 this
  • 使用getApplicationContext()
  • 使用getBaseContext()
  • Use MyActivity.this or just this
  • Use getApplicationContext()
  • Use getBaseContext()

而且我确信还有一两个选择.这些选项都出现在某种教程中,一个使用第一个,下一个使用第三个选项.

And I'm sure there are one or two more options. These options all appear in some sort of tutorial, one uses the first, the next uses the third option.

那么我应该使用哪一个?它甚至重要吗?不同的情况有不同吗?

So which one should I use? Does it even matter? Is it different for different cases?

推荐答案

是的,因情况不同,

这取决于范围.假设您正在一个全局类中创建一个方法,该方法extends Application 来创建一个 Toast,该方法在您的 的每个类中使用应用程序 你可以使用 getApplicationContext() 来创建它.

It depends on the scope. Suppose if you are creating a method in a global class that extends Application to create a Toast that is used in every class of your Application you can use getApplicationContext() to create it.

如果您想创建一个仅限于该特定活动的视图,您可以使用 Activity.this

If you want to create a view that is restricted to that particular Activity you can use Activity.this

另外,如果你想在某个内部类中创建一个 AlertDialog,比如 AsyncTask,那么你必须使用 Activity.this,因为 AlertDialog> 将链接到 Activity 本身.

Also if you want to create an AlertDialog in some inner class say AsyncTask, then you have to use Activity.this, because the AlertDialog is to be linked to Activity itself.

也不要使用 getBaseContext(),只需使用您拥有的 Context.要获得更多信息,你可以看到 这个答案.

Also don't use getBaseContext() just use the Context that you are having. For getting further information for the same you can see this Answer.

所以,真正的问题的答案是使用 Activity.this 来启动一个新的 Activity.

So, the answer to the real question is better to use Activity.this to start a new Activity.

Intent intent = new Intent(Current_Activity.this, Calling.class);
startActivity(intent);

这篇关于使用 Context 启动另一个 Activity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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