1

我从应用程序中删除了操作栏,所以我需要创建按钮来自己打开抽屉 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);
            }
        });

片段成就.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>

成就片段.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$1.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)
4

5 回答 5

10

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

而是在您的活动中创建方法并从您的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();
         }
});
于 2017-03-10T09:32:42.643 回答
2

在抽屉所在的 MainActivity 中声明它,如下所示

public DrawerLayout drawer;

并在onCreate与上述相同的活动(MainActivity)中

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

在仅附加到您的主要活动的片段中

button.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
           ((MainActivity) getActivity()).drawer.openDrawer(Gravity.START);
        }
    });
于 2017-03-10T09:34:29.983 回答
1

尝试这个

button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                DrawerLayout drawer = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
                drawer.openDrawer(Gravity.START);
            }
        });
于 2017-03-10T09:28:10.833 回答
1

从 Fragment 到其 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();

请务必在您的活动中实现监听器和函数 openDrawer 和 closeDrawer

public class NavDrawerActivity extends AppCompatActivity
    implements AchievementsFragment.OnFragmentInteractionListener{
       //some code
    }
于 2017-03-10T10:00:58.213 回答
0

在 Kotlin 中,它将是

在您的活动添加方法中

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

在片段调用方法中

(activity as MyActivity?)?.openDrawer()

打开抽屉,希望它可以帮助某人

于 2021-07-20T18:03:07.533 回答