以编程方式进入主屏幕
当用户单击按钮时,我想在 Android 中以编程方式转到主屏幕。这怎么能做到呢?
I want to go to the home screen programmatically in Android when the user clicks on button. How can this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以通过 Intent 来完成此操作。
此意图将启动用户定义的启动器应用程序。请小心这一点,因为如果用户不希望发生这种情况,这看起来就像您的应用程序崩溃了。
如果您希望在您的应用程序中构建退出按钮,请阅读 退出按钮
You can do this through an Intent.
This Intent will start the launcher application that the user has defined. Be careful with this because this will look like your application crashed if the user does not expect this.
If you want this to build an exit button from your app please read this article on exit Buttons in Android
一行解决方案
它将表现为按下主页按钮
One line solution
it will behave as Home Button is pressed
Janusz 的回答非常棒。
我唯一想补充的是,您可以在不引用当前活动的情况下转到主屏幕,这对评论来说有点太长了。
由于
startActivity()
,Janusz 的代码需要从 Activity 或 Fragment 调用,为了解决这个问题,您可以在应用程序文件中存储对应用程序上下文的静态引用:
现在您可以向用户发送从应用程序中的任何类到设备主屏幕,而不仅仅是活动、片段或引用当前活动的其他类(您可以决定这是好事还是坏事):
Janusz's answer is great.
The only thing I want to add, which is a little too long for a comment, is that you can go to the home screen without having a reference to the current activity.
Janusz's code needs to be called from an Activity or Fragment due to
startActivity()
,To get around this, you can store a static reference to your apps Context in your application file:
Now you can send the user to the device home screen from any class in your app, not just Activities, Fragments, or other Classes with a reference to the current Activity (you can decide whether this is a good or bad thing):
来自 Android 开发人员 站点
以下是您可以指定的其他操作的一些示例使用这些附加参数作为意图:
From Android developer site
Here are some examples of other operations you can specify as intents using these additional parameters:
我知道这有点晚了,但我也遇到了同样的问题,这是我解决的方法。返回到您的
MainActivity
,您需要从现有的Activity
添加标志。现在,当您按下后退按钮时,
MainActivity
处于活动状态,它将转到主屏幕。I know this is a bit late but I also ran into the same problem and here is how I resolved it. Going back to your
MainActivity
you need to add flags from the exitingActivity
Now when you pressed the back button being
MainActivity
the active one, it will go to home screen.