Android Studio 在片段中打开抽屉

Android Studio open Drawer in fragment

我从应用程序中删除了操作栏,因此我需要创建按钮来自己打开抽屉 Activity 上的按钮工作正常但是当我在片段应用程序中使用它时停止工作(当我调用片段时)

我在 Activity 中使用的代码(工作正常的代码)

 ImageButton btn = (ImageButton)findViewById(R.id.drawerButton);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                drawer.openDrawer(Gravity.START);
            }
        });

fragment_achievements.xml

<android.support.constraint.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="layout.AchievementsFragment">

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="28dp"
        android:layout_height="29dp"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:background="@android:color/transparent"
        android:scaleType="fitCenter"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_menu_button" />

    <WebView
        android:id="@+id/web_ach"
        android:layout_width="409dp"
        android:layout_height="602dp"
        android:layout_marginBottom="-9dp"
        android:layout_marginLeft="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        tools:layout_editor_absoluteY="56dp" />

</android.support.constraint.ConstraintLayout>

AchievementsFragment.java

package layout;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;

import th.ac.sd.sdschoolnd.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class AchievementsFragment extends Fragment {


    public AchievementsFragment() {
        // Required empty public constructor
    }

    public WebView mWebView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.fragment_achievements, container, false);
        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.fragment_snews, container, false);
        View v=inflater.inflate(R.layout.fragment_achievements, container, false);
        mWebView = (WebView) v.findViewById(R.id.web_ach);
        mWebView.loadUrl("http://www.sd.ac.th/main/wp-content/WebApps/android/rss_achievements.html");
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        // Force links and redirects to open in the WebView instead of in a browser
        mWebView.setWebViewClient(new WebViewClient());

        ImageButton button = (ImageButton) getView().findViewById(R.id.drawerButton);
        button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                DrawerLayout drawer = (DrawerLayout) getView().findViewById(R.id.drawer_layout);
                drawer.openDrawer(Gravity.START);
            }
        });
        return v;
    }

}

错误日志

                                                                     [ 03-10 16:27:00.791 22121:22160 D/         ]
                                                                     HostConnection::get() New Host Connection established 0x947f8c00, tid 22160
03-10 16:27:00.794 22121-22161/th.ac.sd.sdschoolnd E/chromium: [ERROR:gles2_cmd_decoder.cc(2210)] [GroupMarkerNotSet(crbug.com/242999)!:546A05A2]GL ERROR :GL_INVALID_OPERATION : BackFramebuffer::Create: <- error from previous GL command
03-10 16:27:00.798 22121-22160/th.ac.sd.sdschoolnd W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
03-10 16:27:00.798 22121-22160/th.ac.sd.sdschoolnd D/OpenGLRenderer: Swap behavior 0
03-10 16:27:00.857 22121-22121/th.ac.sd.sdschoolnd W/art: Attempt to remove non-JNI local reference, dumping thread
03-10 16:27:00.950 22121-22121/th.ac.sd.sdschoolnd W/art: Attempt to remove non-JNI local reference, dumping thread
03-10 16:27:00.984 22121-22121/th.ac.sd.sdschoolnd W/cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 22121
03-10 16:27:03.877 22121-22121/th.ac.sd.sdschoolnd W/art: Attempt to remove non-JNI local reference, dumping thread
03-10 16:27:03.895 22121-22121/th.ac.sd.sdschoolnd W/cr_AwContents: onDetachedFromWindow called when already detached. Ignoring
03-10 16:27:03.897 22121-22121/th.ac.sd.sdschoolnd I/cr_Ime: ImeThread is not enabled.
03-10 16:27:03.902 22121-22161/th.ac.sd.sdschoolnd E/chromium: [ERROR:gles2_cmd_decoder.cc(2210)] [GroupMarkerNotSet(crbug.com/242999)!:546F05A2]GL ERROR :GL_INVALID_OPERATION : BackFramebuffer::Create: <- error from previous GL command
03-10 16:27:03.902 22121-22121/th.ac.sd.sdschoolnd D/AndroidRuntime: Shutting down VM
03-10 16:27:03.902 22121-22121/th.ac.sd.sdschoolnd E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: th.ac.sd.sdschoolnd, PID: 22121
                                                                     java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                                                                         at layout.AchievementsFragment.onCreateView(AchievementsFragment.java:44)
                                                                         at android.support.v4.app.Fragment.performCreateView(Fragment.java:2189)
                                                                         at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
                                                                         at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                                                                         at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                                                                         at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
                                                                         at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
                                                                         at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
                                                                         at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
                                                                         at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2008)
                                                                         at android.support.v4.app.FragmentManagerImpl.run(FragmentManager.java:710)
                                                                         at android.os.Handler.handleCallback(Handler.java:751)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                         at android.os.Looper.loop(Looper.java:154)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

试试这个

button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                DrawerLayout drawer = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
                drawer.openDrawer(Gravity.START);
            }
        });

那是因为 您正试图在 fragment 中找到 drawerLayout,它不在片段中,而是在您的 activity 中。
这是你的错误 - DrawerLayout drawer = (DrawerLayout) getView().findViewById(R.id.drawer_layout);

而是在您的 activity 中创建方法并从您的 fragment 中调用该方法

这将是 YourActivity 中的方法

public void openDrawer() {
   DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                drawer.openDrawer(Gravity.START);
}

现在从您的片段中调用此方法 -

((YourActivity) getActivity()).openDrawer();

最后,您在片段中的代码将是:-

button.setOnClickListener(new View.OnClickListener(){
         @Override
         public void onClick(View v) {
              ((YourActivity) getActivity()).openDrawer();
         }
});

Declare this in MainActivity where drawer is located as below

public DrawerLayout drawer;

and in onCreate of same activity (MainActivity) as above

drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

In Fragment which is attached to your main activity only

button.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
           ((MainActivity) getActivity()).drawer.openDrawer(Gravity.START);
        }
    });

片段与其 activity 通信的最佳方式是通过接口。 在您的片段中包括:

private AchievementsFragment.OnFragmentInteractionListener mListener;

public interface OnFragmentInteractionListener {
        void openDrawer();
        void closeDrawer();
    }

@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

无论你想在片段中打开抽屉,你都可以调用

mListener.openDrawer();

确保在您的 activity

中实现侦听器和函数 openDrawer 和 closeDrawer
public class NavDrawerActivity extends AppCompatActivity
    implements AchievementsFragment.OnFragmentInteractionListener{
       //some code
    }

在 Kotlin 中它将是

在你的activity添加方法

fun openDrawer() {
        val drawer = findViewById<View>(R.id.drawerLayout) as DrawerLayout
        drawer.openDrawer(Gravity.LEFT, true)
    }

在片段调用方法中

(activity as MyActivity?)?.openDrawer()

打开抽屉,希望对大家有所帮助