[英]How to handle back button in activity if I have multiple screens in an activity
I have an activity which has multiple screens depending on which buttons the user clicks. 我有一个活动,该活动具有多个屏幕,具体取决于用户单击的按钮。
What should I do if I need to handle back button in this activity. 如果需要在此活动中处理后退按钮,该怎么办。 ie When I press to back button it has to go previous screen of my activity. 即,当我按下返回按钮时,它必须进入我的活动的上一个屏幕。
I am really new to android. 我真的是android新手。 can any body help me to solve this problem 谁能帮我解决这个问题
Thanks for reading. 谢谢阅读。
I guess that by multiple screens you mean you have some layouts and change them with setContentView()
. 我猜通过多个屏幕,您的意思是您拥有一些布局,并使用setContentView()
对其进行了更改。 You'll have to override the back button's behavior, keep a history of user navigation between various screens (if there's no forced path) and have the back button code set content to the previous screen. 您将必须覆盖后退按钮的行为,保留各种屏幕之间的用户导航历史记录(如果没有强制路径),并且必须将后退按钮代码设置为上一个屏幕的内容。
Overriding the back button is easy if you're on API >= 5: see onBackPressed() . 如果您使用的API> = 5,则覆盖后退按钮很容易:请参见onBackPressed() 。
If you want also backward compatibility you'll find something here and here . 如果您还希望向后兼容,那么您会在这里和这里找到一些东西。
As this is usually all done automatically by Android with activities, consider having multiple activities instead of a single activity with multiple screens. 由于这通常都是由Android通过活动自动完成的,因此请考虑使用多个活动,而不是使用多个屏幕进行单个活动。
在您的活动中重写onBackPressed()函数,并在其中写入所需的代码以进行意图触发。
You can do this by handling the KeyDown event and adding some condition( like taking a static variable and at each activity assign different value to the static variable ) at each actvity. 您可以通过处理KeyDown事件并在每个活动中添加一些条件(例如获取静态变量,并在每个活动中为静态变量分配不同的值)来做到这一点。 See the following code: 请参见以下代码:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
if(condition 1)
{
Intent i=new Intent("com.prac.A"); // A is your another activity in com.prac package
startAcitvity(i);
}
else if(condition 2)
{
Intent i=new Intent("com.prac.B");
startAcitvity(i);
}
else
{
Intent i=new Intent("com.prac.C");
startAcitvity(i);
}
}
return false;
}
Hope this will help you. 希望这会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.