如何将导航抽屉切换添加到工具栏

时间:2018-09-06 22:07:43

标签: 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) {

}
}

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

1 个答案:

答案 0 :(得分:1)

您还应该共享已经具有导航抽屉的layout&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中复制哪些代码。