Android Studio 在片段中打开抽屉 [英] Android Studio open Drawer in fragment

查看:42
本文介绍了Android Studio 在片段中打开抽屉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I remove the actionbar from application so I need to create button to open drawer myself button on Activity works fine but when I'm using it in fragment application stop working (when I call the fragment)

我在 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$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)

推荐答案

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

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

That is because you are trying to find drawerLayout in fragment which is not in fragment but in your activity.
This is your mistake - DrawerLayout drawer = (DrawerLayout) getView().findViewById(R.id.drawer_layout);

Instead create method in your activity and call that method from your fragment

这将是 YourActivity 中的方法

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

现在从你的片段中调用这个方法 -

Now call this method from your fragment -

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

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

Finally, your code in fragment will be:-

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

这篇关于Android Studio 在片段中打开抽屉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆