CoordinatorLayout无法强制转换为android.support.v4.widget.DrawerLayout

时间:2015-10-24 02:31:50

标签: android-activity android-studio splash-screen android-fragmentactivity android-actionbaractivity

该应用程序初始化为启动,显示并运行良好。 然后,当您尝试访问菜单栏时,应用程序崩溃。

这是我的Main_Activity.j

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    /*
         DECLARACIONES
         */
    private DrawerLayout drawerLayout;
    private ListView drawerList;
    private ActionBarDrawerToggle drawerToggle;

    private CharSequence activityTitle;
    private CharSequence itemTitle;
    private String[] tagTitles;

    public class MainActivity extends AppCompatActivity {
        /*
             DECLARACIONES
             */
        private DrawerLayout drawerLayout;
        private ListView drawerList;
        private ActionBarDrawerToggle drawerToggle;
        private CharSequence activityTitle;
        private CharSequence itemTitle;
        private String[] tagTitles;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            itemTitle = activityTitle = getTitle();
            tagTitles = getResources().getStringArray(R.array.Tags);
            drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawerList = (ListView) findViewById(R.id.left_drawer);
            // Setear una sombra sobre el contenido principal cuando el drawer se despliegue
            drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        //Crear elementos de la lista
        ArrayList<DrawerItem> items = new ArrayList<DrawerItem>();
        items.add(new DrawerItem(tagTitles[0], R.drawable.ic_html));
        items.add(new DrawerItem(tagTitles[1], R.drawable.ic_css));
        items.add(new DrawerItem(tagTitles[2], R.drawable.ic_javascript));
        items.add(new DrawerItem(tagTitles[3], R.drawable.ic_angular));
        items.add(new DrawerItem(tagTitles[4], R.drawable.ic_python));
        items.add(new DrawerItem(tagTitles[5], R.drawable.ic_ruby));

        // Relacionar el adaptador y la escucha de la lista del drawer
        drawerList.setAdapter(new DrawerListAdapter(this, items));
        drawerList.setOnItemClickListener(new DrawerItemClickListener());

        // Habilitar el icono de la app por si hay algún estilo que lo deshabilitó
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        // Crear ActionBarDrawerToggle para la apertura y cierre
        drawerToggle = new ActionBarDrawerToggle(
                this,
                drawerLayout,
                R.drawable.ic_drawer,
                R.string.drawer_open,
                R.string.drawer_close
        ) {
            public void onDrawerClosed(View view) {
                getSupportActionBar().setTitle(itemTitle);

                /*Usa este método si vas a modificar la action bar
                con cada fragmento
                 */
                //invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getSupportActionBar().setTitle(activityTitle);

                /*Usa este método si vas a modificar la action bar
                con cada fragmento
                 */
                //invalidateOptionsMenu();
            }
        };
        //Seteamos la escucha
        drawerLayout.setDrawerListener(drawerToggle);
        if (savedInstanceState == null) {
            selectItem(0);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (drawerToggle.onOptionsItemSelected(item)) {
            // Toma los eventos de selección del toggle aquí
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /* La escucha del ListView en el Drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
            drawerLayout.closeDrawer(drawerList);
        }
    }

    private void selectItem(int position) {
        // Reemplazar el contenido del layout principal por un fragmento
        ArticleFragment fragment = new ArticleFragment();
        Bundle args = new Bundle();
        args.putInt(ArticleFragment.ARG_ARTICLES_NUMBER, position);
        fragment.setArguments(args);

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

        // Se actualiza el item seleccionado y el título, después de cerrar el drawer
        drawerList.setItemChecked(position, true);
        setTitle(tagTitles[position]);
        drawerLayout.closeDrawer(drawerList);
    }

    /* Método auxiliar para setear el titulo de la action bar */
    @Override
    public void setTitle(CharSequence title) {
        itemTitle = title;
        getSupportActionBar().setTitle(itemTitle);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sincronizar el estado del drawer
        drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Cambiar las configuraciones del drawer si hubo modificaciones
        drawerToggle.onConfigurationChanged(newConfig);
    }
}

这是我的content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#111"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" />
</RelativeLayout>

这是我的activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    android:id="@+id/drawer_layout"
    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" android:fitsSystemWindows="true"
    tools:context=".MainActivity">
    <android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
        android:layout_width="match_parent" 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>
    <include layout="@layout/content_main" />
    <android.support.design.widget.FloatingActionButton android:id="@+id/fab"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>

错误

    10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime: FATAL EXCEPTION: main`enter code here
    10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime: Process: com.example.german.pedorreta, PID: 22911
    10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.german.pedorreta/com.example.german.pedorreta.MainActivity}: java.lang.ClassCastException:
android.support.design.widget.CoordinatorLayout cannot be cast to
android.support.v4.widget.DrawerLayout
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta
E/AndroidRuntime:
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at
android.app.ActivityThread.access$800(ActivityThread.java:139)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.os.Handler.dispatchMessage(Handler.java:102)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.os.Looper.loop(Looper.java:136)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.ActivityThread.main(ActivityThread.java:5086)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at dalvik.system.NativeStart.main(Native Method)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:Caused by: java.lang.ClassCastException: android.support.design.widget.CoordinatorLayout cannot be cast to android.support.v4.widget.DrawerLayout
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at com.example.german.pedorreta.MainActivity.onCreate(MainActivity.java:44)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.Activity.performCreate(Activity.java:5248)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.ActivityThread.access$800(ActivityThread.java:139) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.os.Handler.dispatchMessage(Handler.java:102) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.os.Looper.loop(Looper.java:136) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at android.app.ActivityThread.main(ActivityThread.java:5086) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at java.lang.reflect.Method.invokeNative(Native Method) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at java.lang.reflect.Method.invoke(Method.java:515) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime:at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
10-24 03:58:12.195 22911-22911/com.example.german.pedorreta E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:2)

您在activity_main.xml

中遗漏了DrawerLayout

尝试使用CoordinatorLayout

包裹DrawerLayout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    ...

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

    <android.support.design.widget.NavigationView
        android:id="@+id/drawer"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:menu="@menu/main_menu"/>

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