在我的MainActivity中,我有5个按钮,其中4个打开aWebViewActivity以显示静态html内容。第5个按钮转到PumpsActivity,其中包含另外5个按钮,这些按钮还打开WebViewActivity以显示静态html页面。
现在来谈谈这个问题:
我希望能够从WebViewActivity导航到适当的父活动。例如:如果WebViewActivity是从MainActivity调用的,则向上导航将使用户转到MainActivity。按照android.developer.com指南,这很容易实现。
但是如何让WebViewActivity导航到PumpsActivity?如何检查WebViewActivity是从哪个活动开始的?
MyWebViewActivity中的相关代码(与guide中的基本相同):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web_view);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    Intent intent = getIntent();
    setTitle(intent.getStringExtra("WEBVIEW_TITLE"));

    webview = (WebView) findViewById(R.id.wvMyWebView);
    WebSettings webSettings = webview.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webview.loadUrl(intent.getStringExtra("WEBVIEW_URL"));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // This is called when the Home (Up) button is pressed
            // in the Action Bar.
            Intent parentActivityIntent = new Intent(this, MainActivity.class);

            parentActivityIntent.addFlags(
                    Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(parentActivityIntent);
            finish();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

最佳答案

正如leonidos建议的那样,您可以添加一个参数,但这会引入额外的耦合,我感觉到父类只有活动超类的共同点,传递活动类型并不理想。
一种方法是在webviewactivity中添加另一个字符串来指示调用活动。在onoptionsitemselected中,您可以额外检查父字符串以查看哪个活动调用了它,并根据需要导航到该活动。

10-08 12:21