转到上一个视图或离开应用程序onKeydown

时间:2014-08-25 13:26:00

标签: android view onkeydown

我有1个视图(首页) 第二个视图(webview) 我想要做的是,当用户在Webview上时,如果他按后退键,他将返回到frontpageview,如果他在frontpageview上,应用程序将关闭。

我尝试过这样的事情:

            @Override
        public boolean onKeyDown(int keyCode, KeyEvent event){

            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                if(findViewById(R.id.frontpage_view).getTag().equals("front")) 
                    finish();
                else if(findViewById(R.id.webView_web_app).getTag().equals("webv")) 
                    setContentView(R.layout.frontpage);}
                return true;}}

这是来自“frontpage”(开头)的xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
   android:id="@+id/frontpage_view"
android:tag="front"
 >

和Webview

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WebAppActivity"
 >

<WebView
    android:id="@+id/webView_web_app"
    android:tag="webv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true" />

当布局是首页时,它会在按下后退键时离开应用程序。 但是一旦我在webview布局上,当我按下反键时应用程序崩溃。 我这样做是对的吗?

1 个答案:

答案 0 :(得分:0)

使用活动和片段管理您的观看次数。阅读proper back navigation

相关问题