簡體   English   中英

Android后退按鈕不會返回上一個活動

[英]Android Back Button Doesn't Return to Previous Activity

我有一個有兩個活動的應用程序:MainActivity和SettingsActivity。 MainActivity有一個菜單,其中包含一個“設置”菜單項。 單擊此菜單項時,它會以意圖啟動SettingsActivity。 活動開始后,我點擊左上角的后退按鈕,沒有任何反應。 我假設自從使用intent啟動活動后,活動堆棧將自動管理。 我想回到MainActivity。 這個假設我錯了嗎?

MainActivity.onMenuItemSelected

public boolean onMenuItemSelected(int featureId, MenuItem item) {
    int itemID = item.getItemId();

    if(itemID == R.id.settings) {
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
    }

    return true;
}

SettingsActivity

public class SettingsActivity extends PreferenceActivity {

    public static final String TEST = "test";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }
}

在您的SettingsActivity您需要覆蓋onOptionsItemSelected以啟用Action Bar左上角的后退按鈕以便返回。 它本身並不知道點擊它需要做什么。 android.R.id.home案例中你可以調用finish() 這將完成您當前的活動,然后您將返回啟動它的MainActivity 例如:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

為了完整起見,要啟用主頁按鈕,您可以在SettingsActivity onCreate()中添加以下內容:

getActionBar().setDisplayHomeAsUpEnabled(true);

根據setDisplayHomeAsUpEnabled()的文檔

It is to show the user that selecting home will return one level up rather than to the top level of the app.

希望這可以幫助。

只需在OnCreate方法中添加這些行

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

並覆蓋此方法以向后退按鈕添加功能:

   @Override
public boolean onOptionsItemSelected(MenuItem item)
{
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    } else if(id==android.R.id.home)
    {
     finish();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

希望它能幫到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM