Android Studio后退按钮问题

时间:2016-10-27 02:04:22

标签: java android android-studio

到目前为止。我在Android Studio上创建了一个简单的测验应用程序。一切正常,包括当我从FirstActivity.java转到Next Activity(名为SecondActivity.java),并在按下按钮时关闭第一个带有finish()的活动,如下面的代码所示:

 public void onClick () {   

    button_next = (Button)findViewById(R.id.nextbtn);


            button_next.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(FirstActivity.this, SecondActivity.class));
                    finish();


                }
            });

代码工作正常但是当我尝试从第二个活动转到第一个活动(关闭第二个活动并返回到第一个活动)时,finish()和onBackPressed()都不起作用,它只是关闭完全应用程序,我按下按钮后需要什么代码,关闭SecondActivity.class并转到FirstActivity.class?

2 个答案:

答案 0 :(得分:0)

如果您想返回之前的活动,请在更改活动后不要完成。

library(RSelenium)

pJS <- phantom() # start phantomjs

appURL <- 'https://www.optionslam.com/accounts/login/'
remDr <- remoteDriver(browserName = "phantomjs")
remDr$open()
remDr$navigate(appURL)
remDr$findElement("id", "id_username")$sendKeysToElement(list("user"))
remDr$findElement("id", "id_password")$sendKeysToElement(list("password", key='enter'))

appURL <- 'https://www.optionslam.com/earnings/stocks/MSFT?page=-1'
remDr$navigate(appURL)

答案 1 :(得分:0)

如果您有这么多活动,还有另一种处理活动生命周期的方法:

if [ "$(( width >= 500 ? 1 : 0))" = 1 ]

在FirstActivity,你应该添加

public class MyActivityManager { private static MyActivityManager instance; private Stack<Activity> activityStack;//activity's stack private MyActivityManager() { } //singleton public static MyActivityManager getInstance() { if (instance == null) { instance = new MyActivityManager(); } return instance; } //push an activity to stack public void pushOneActivity(Activity actvity) { if (activityStack == null) { activityStack = new Stack<Activity>(); } activityStack.add(actvity); } //get last activity,fifo public Activity getLastActivity() { return activityStack.lastElement(); } //remove an activity public void popOneActivity(Activity activity) { if (activityStack != null && activityStack.size() > 0) { if (activity != null) { activity.finish(); activityStack.remove(activity); activity = null; } } } //finish all activity public void finishAllActivity() { if (activityStack != null) { while (activityStack.size() > 0) { Activity activity = getLastActivity(); if (activity == null) break; popOneActivity(activity); } } } }

在SecondActivity,您想要参加FirstActivity或其他活动:

MyActivityManager.getInstance().pushOneActivity(FirstActivity.this);