java - 如何向工具栏添加抽屉导航切换

标签 java android android-studio

我已经完成了所有操作,我可以看到抽屉导航,但我的应用程序崩溃了。任何人都可以解释以下代码中的问题是什么。现在,每当我尝试打开 ForumActivty 时,它就会崩溃。

public class ForumActivity extends AppCompatActivity implements AdvancedWebView.Listener{

public AdvancedWebView webView;
private ProgressBar mPbar = null;

private static final String  url = "https://discuss.flarum.org/";
String webURL, webTitle ;

private DrawerLayout mDrawerLayout;
private Fragment fragment;
private FragmentManager fragmentManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ((CustomApplication)getApplication()).checkUserLogin();
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    setContentView(R.layout.activity_forum);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    Bundle bundle = getIntent().getExtras();
    if(bundle != null){
        fragment = new ProfileFragment();
    }else{
        fragment = new TopicFragment();
    }

    fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.fragment_content, fragment).commit();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            int id = item.getItemId();

            if (id == R.id.nav_topic) {
                fragment = new TopicFragment();
            }
            else if(id == R.id.nav_profile){
                fragment = new ProfileFragment();
            }
            else if(id == R.id.nav_scores){
                fragment = new ScoreFragment();
            }
            else if(id == R.id.nav_share){
                fragment = new ScoreFragment();
            }
            else if(id == R.id.nav_contact){
                startActivity(new Intent(ForumActivity.this, ContactActivity.class));
            }
            else if(id == R.id.nav_settings){
                fragment = new SettingsFragment();
            }
            else if(id == R.id.nav_logout){
                ((CustomApplication)getApplication()).getShared().setUserData("");
                Intent logoutIntent = new Intent(ForumActivity.this, LoginActivity.class);
                logoutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(logoutIntent);
                finish();
            }

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.fragment_content, fragment).commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
            return true;
        }

    });

    mPbar = (ProgressBar) findViewById(R.id.loader);

    webView = (AdvancedWebView) findViewById(R.id.newWeb);
    webView.loadUrl(url);
    webView.setListener(this, this);

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    webSettings.setAllowFileAccess(true);

    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);

    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            AdvancedWebView newWebView = new AdvancedWebView(ForumActivity.this);
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(newWebView);
            resultMsg.sendToTarget();
            return true;
        }
    });

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
    } else {
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    webView.setWebViewClient(new WebViewClient(){
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            mPbar.setVisibility(View.VISIBLE);
        }
        public void onPageFinished(WebView view, String url) {
            mPbar.setVisibility(View.GONE);
        }
    });

    webView.setOnKeyListener( new View.OnKeyListener() {
        @Override
        public boolean onKey( View v, int keyCode, KeyEvent event ) {
            if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
                webView.goBack();
                return true;
            }
            return false;
        }
    });

    webView.setThirdPartyCookiesEnabled(true);
    webView.setCookiesEnabled(true);

}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case android.R.id.home:
            mDrawerLayout.openDrawer(GravityCompat.START);
            return true;
    }

    return super.onOptionsItemSelected(item);


}

@Override
protected void onResume() {
    super.onResume();
    webView.onResume();
}

@Override
protected void onPause() {
    webView.onPause();
    super.onPause();
}

@Override
protected void onDestroy() {
    webView.onDestroy();
    super.onDestroy();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    webView.onActivityResult(requestCode, resultCode, intent);
}

@Override
public void onBackPressed() {
    if (!webView.onBackPressed()) { return; }
    super.onBackPressed();
}


@Override
public void onPageStarted(String url, Bitmap favicon) {

}

@Override
public void onPageFinished(String url) {
    webURL = webView.getUrl();
    webTitle = webView.getTitle();

}

@Override
public void onPageError(int errorCode, String description, String failingUrl) {

}

@Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {

}

@Override
public void onExternalPageRequest(String url) {

}
}

我知道我在上面做错了什么,但我已经将所有内容都包含在布局中。如果有人能帮忙那就太好了

最佳答案

您还应该共享已经有抽屉导航的布局和 Activity 的代码。无论如何,您可以关注this指南。

对于您的布局文件,您需要将 CoordinatorLayout像这样在 DrawerLayout 中添加一个 NavigationView(检查已经有抽屉导航的其他 Activity 的 xml 布局并复制 <android.support.design.widget.NavigationView> 并替换为下面示例中的布局):

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
                    android:id="@+id/drawer_layout"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:fitsSystemWindows="true">

    <android.support.design.widget.CoordinatorLayout
        xmlns:app="http://schemas.android.com/apk/res-auto"
                    android:id="@+id/coordinator_layout"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:fitsSystemWindows="true">

        <android.support.design.widget.AppBarLayout
                   android:layout_width="match_parent"
                   android:layout_height="wrap_content"
                   android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
        </android.support.design.widget.AppBarLayout>

        <im.delight.android.webview.AdvancedWebView
            android:id="@+id/newWeb"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            ></im.delight.android.webview.AdvancedWebView>

        <ProgressBar
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/loader"
            android:layout_weight="1"
            android:layout_gravity="center_vertical|center_horizontal|center"/>

    </android.support.design.widget.CoordinatorLayout>

    <!-- Replace this with the one in other activity layout -->
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:menu="@menu/drawer_view"/>

</android.support.v4.widget.DrawerLayout>

之后,您需要在 Activity 类中添加一些代码。您可以检查我上面放置的链接,阅读后您可以了解需要从已经具有抽屉导航的其他 Activity 复制哪些代码。

关于java - 如何向工具栏添加抽屉导航切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52212721/

相关文章:

java - java包名为什么要小写?

java - 如何使用ant build.xml将源代码添加到jar文件

java - 如何将自定义 ScrollPanel 的高度设置为 100%?

android - 我的 ListView 背景选择器不会突出显示所选行

javascript - A/libc : Fatal signal 11 (SIGSEGV), 代码 1 (SEGV_MAPERR), tid 8890 (RenderThread) 中的故障地址 0x20, pid 8833

java - 为什么在使用 MouseAdapter 时没有收到 mouseDragged 事件?

android - 如何仅从 WebViewClient 的新 onReceivedError 中的主页检测错误

Android谷歌地图,谷歌地点,北纬超过南纬

android - 通过蓝牙将流发送到已连接的设备

java - JSON 对象/数组 - Java 类