Android - использовать onBackPressed как для фрагмента, так и для DrawerLayout в java - PullRequest
0 голосов
/ 21 июня 2020

У меня есть один довольно сложный вопрос о том, как реализовать onBackPressed как для DrawerLayout, который находится в MainActivity, так и во фрагменте для webView.

Ниже представлена ​​древовидная структура моего приложения android.


                                ----------- HomeFragment(WebView)
                               |
MainActivity(Drawer)----------- ----------- DashBoardFragment
                               |
                                ----------- NotificationFragment

activity_main. xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
    android:id="@+id/drawer"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <fragment
            android:id="@+id/main"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:defaultNavHost="true"
            app:navGraph="@navigation/mobile_navigation"
            tools:ignore="FragmentTagUsage" />

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="0dp"
            android:layout_marginEnd="0dp"
            android:background="?android:attr/windowBackground"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:menu="@menu/bottom_nav_menu" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.material.navigation.NavigationView
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:menu="@menu/bottom_nav_menu"
        android:id="@+id/navigationView">

    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>


MainActivity. java


public class MainActivity extends AppCompatActivity {

/* code of Drawer is here */

    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START))
        {
            drawer.closeDrawer(GravityCompat.START);
        }
        else if (webView.canGoBack()){
            webView.goBack();
        }else {
            super.onBackPressed();
        }
    }
}

Home_Fragment. xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.home.HomeFragment">

    <LinearLayout
        android:layout_width="409dp"
        android:layout_height="729dp"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="1dp"
        tools:layout_editor_absoluteY="1dp"
        tools:ignore="MissingConstraints">

        <WebView
            android:id="@+id/myWebView"
            android:layout_width="match_parent"
            android:layout_height="601dp" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

HomeFragment. java

public class HomeFragment extends Fragment {

   /* code of WebView is here */
}

/* here is problem */

    @Override
    public void onBackPressed() {
        /* have place code here to handle back Press button */
    }
}

Мой запрос: -

  1. Мне нужно использовать метод onBackPressed () в MainActivity. java для DrawerLayout.
  2. И метод onBackPressed () в HomeFragment. java для WebView.

Проблема в том, что я могу использовать метод onBackPressed () либо в MainActivity. java, либо в HomeFragment. java, но мне нужно использовать метод onBackPressed () в обоих файлах.

Посмотрите на снимок экрана, красный квадрат - это мой веб-просмотр, который находится в Home_Fragment, мне нужен 1 метод onBackPressed для всего приложения, я имею в виду Drawerlayout и 1 метод onBackPressed () для внутри webView

Look at screenshot, red square is my webview which is in Home_Fragment

Its the opened post inside the webview, onBackPressed Method will send me back to my webview main page when i click backButton

Its the opened post inside the webview, onBackPressed Method will send me back to my webview main page when i click backButton

But I am getting this message when i press backbutton

введите описание изображения здесь

[РЕДАКТИРОВАТЬ 1]: код ошибки в терминале RUN

E/InputEventSender: Exception dispatching finished signal.
E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.webkit.WebView.canGoBack()' on a null object reference
        at com.example.modapk4everyone.MainActivity.onBackPressed(MainActivity.java:60)
        at android.app.Activity.onKeyUp(Activity.java:3641)
        at android.view.KeyEvent.dispatch(KeyEvent.java:2844)
        at android.app.Activity.dispatchKeyEvent(Activity.java:3958)
        at androidx.core.app.ComponentActivity.superDispatchKeyEvent(ComponentActivity.java:122)
        at androidx.core.view.KeyEventDispatcher.dispatchKeyEvent(KeyEventDispatcher.java:84)
        at androidx.core.app.ComponentActivity.dispatchKeyEvent(ComponentActivity.java:140)
        at androidx.appcompat.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:558)
        at androidx.appcompat.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
        at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:2814)
        at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:367)
        at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:5414)
        at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5282)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4789)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4842)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4808)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4948)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4816)
        at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:5005)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4789)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4842)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4808)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4816)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4789)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4842)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4808)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4981)
        at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:5142)
        at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:3064)
        at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:2607)
        at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:2598)
        at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:3041)
        at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:143)
        at android.os.MessageQueue.nativePollOnce(Native Method)
        at android.os.MessageQueue.next(MessageQueue.java:336)
        at android.os.Looper.loop(Looper.java:174)
        at android.app.ActivityThread.main(ActivityThread.java:7397)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.modapk4everyone, PID: 20714
    java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.webkit.WebView.canGoBack()' on a null object reference
        at com.example.modapk4everyone.MainActivity.onBackPressed(MainActivity.java:60)
        at android.app.Activity.onKeyUp(Activity.java:3641)
        at android.view.KeyEvent.dispatch(KeyEvent.java:2844)
        at android.app.Activity.dispatchKeyEvent(Activity.java:3958)
        at androidx.core.app.ComponentActivity.superDispatchKeyEvent(ComponentActivity.java:122)
        at androidx.core.view.KeyEventDispatcher.dispatchKeyEvent(KeyEventDispatcher.java:84)
        at androidx.core.app.ComponentActivity.dispatchKeyEvent(ComponentActivity.java:140)
        at androidx.appcompat.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:558)
        at androidx.appcompat.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
        at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:2814)
        at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:367)
        at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:5414)
        at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5282)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4789)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4842)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4808)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4948)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4816)
        at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:5005)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4789)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4842)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4808)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4816)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4789)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4842)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4808)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4981)
        at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:5142)
        at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:3064)
        at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:2607)
        at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:2598)
        at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:3041)
        at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:143)
        at android.os.MessageQueue.nativePollOnce(Native Method)
        at android.os.MessageQueue.next(MessageQueue.java:336)
        at android.os.Looper.loop(Looper.java:174)
        at android.app.ActivityThread.main(ActivityThread.java:7397)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
I/Process: Sending signal. PID: 20714 SIG: 9
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...