Load navigation drawer slider with Dynamic Fragments

时间秒杀一切 提交于 2019-12-11 10:29:13

问题


I'm making an Android App for my college using navigation drawer. It has two types of users - students & faculty. So depending upon the email-id/username I want to load the components of respective user in the drawer/slider. I went through this question, which suggests we can use any layout in the child layout: Is it possible to use something other than a listview as sliding drawer in drawerlayout

So in order to implement my logic I wish to use 3 dynamic fragments : login_fragment, student_fragment, faculty_fragment. And then using the username type I will replace the login_fragment with student/faculty_fragment in the drawer. But I'm getting errors in loading the drawer with dynamic fragment.

This is the main_activity code I'm using to load dynamic fragments in the drawer(by drawer I'm mean the slider). The main layout part i.e content_frame is already done using the same approach with no errors.

navigation drawer layout file :

//main_activity.xml layout file
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- As the main content view, the view below consumes the entire
     space available using match_parent in both dimensions. -->
<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<!-- android:layout_gravity="start" tells DrawerLayout to treat
     this as a sliding drawer on the left side for left-to-right
     languages and on the right side for right-to-left languages.
     The drawer is given a fixed width in dp and extends the full height of
     the container. A solid background is used for contrast
     with the content view. -->

 <FrameLayout
    android:id="@+id/left_drawer"
    android:layout_width="320dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="#111" >
</FrameLayout>

This is the .java file for the corresponding layout and I think the error is in loading the drawer list layout :

// Main_Activity
package com.kodevelop.gndec;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration; 
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class LaunchActivity extends FragmentActivity {

private DrawerLayout DrawerLayout;
private ListView DrawerList;
private ActionBarDrawerToggle DrawerToggle;

@SuppressWarnings("unused")
private CharSequence DrawerTitle;
private CharSequence Title;
private String[] ListTitles;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.drawerlist_test);

    Title = DrawerTitle = getTitle();
    ListTitles = getResources().getStringArray(R.array.list_array);
    DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    DrawerList = (ListView) findViewById(R.id.left_drawer);


    // initialize drawer list 
    // Also set a custom shadow that overlays the main content when the drawer opens
    DrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);


    // add fragments to drawer list
    Fragment newFragment;
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    newFragment = new testfragment();
    transaction.replace(R.id.left_drawer, newFragment);
    transaction.addToBackStack(null);
    transaction.commit();

    System.out.println("check1........ + fragment created");

    /*
    // set up the drawer's list view with items and click listener
    DrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_itemlist, ListTitles));
    DrawerList.setOnItemClickListener(new DrawerItemClickListener());
     */

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    DrawerToggle = new ActionBarDrawerToggle(
            this,                  /* host Activity */
            DrawerLayout,         /* DrawerLayout object */
            R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open,  /* "open drawer" description for accessibility */
            R.string.drawer_close  /* "close drawer" description for accessibility */
            ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(Title);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(Title); // same title for open/close drawer
            //getActionBar().setTitle(DrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };
    DrawerLayout.setDrawerListener(DrawerToggle);
    if (savedInstanceState == null) {
        selectItem(0);
    }
}


/**
 * When using the ActionBarDrawerToggle, you must call it during
 * onPostCreate() and onConfigurationChanged()...
 */

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    DrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggle
    DrawerToggle.onConfigurationChanged(newConfig);
}   


// option menu - action bar   
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}


// Called whenever we call invalidateOptionsMenu()
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // If the nav drawer is open, hide action items related to the content view
    boolean drawerOpen = DrawerLayout.isDrawerOpen(DrawerList);
    menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // The action bar home/up action should open or close the drawer.
    // ActionBarDrawerToggle will take care of this.
    if (DrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }


    // Handle action buttons
    switch(item.getItemId()) {
    case R.id.action_websearch:
        // create intent to perform web search for this planet
        Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
        intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
        // catch event that there's no activity to handle intent
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        } else {
            Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}


// Nav Drawer List click
// The click listener for ListView in the navigation drawer
private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);
    }
}

private void selectItem(int position) {

    Fragment newFragment;
    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    switch (position) {
    case 0:
        newFragment = new f1();
        transaction.replace(R.id.content_frame, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();
        break;

    case 1:
        newFragment = new f2();
        transaction.replace(R.id.content_frame, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();
        break;

    case 2:
        newFragment = new f3();
        transaction.replace(R.id.content_frame, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();
        break;

    case 3:
        newFragment = new f4();
        transaction.replace(R.id.content_frame, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();
        break;  


    }
    DrawerList.setItemChecked(position, true);
    setTitle(ListTitles[position]);
    DrawerLayout.closeDrawer(DrawerList);   
}


@Override
public void setTitle(CharSequence title) {
    Title = title;
    getActionBar().setTitle(Title);
}
}

And this is the logcat error list :

    11-24 13:16:53.058: E/Trace(18812): error opening trace file: No such file or directory (2)
11-24 13:16:53.058: W/Trace(18812): Unexpected value from nativeGetEnabledTags: 0
11-24 13:16:53.058: W/Trace(18812): Unexpected value from nativeGetEnabledTags: 0
11-24 13:16:53.058: W/Trace(18812): Unexpected value from nativeGetEnabledTags: 0
11-24 13:16:53.068: W/Trace(18812): Unexpected value from nativeGetEnabledTags: 0
11-24 13:16:53.068: W/Trace(18812): Unexpected value from nativeGetEnabledTags: 0
11-24 13:16:53.108: D/AndroidRuntime(18812): Shutting down VM
11-24 13:16:53.108: W/dalvikvm(18812): threadid=1: thread exiting with uncaught exception (group=0xb2e17908)
11-24 13:16:53.108: E/AndroidRuntime(18812): FATAL EXCEPTION: main
11-24 13:16:53.108: E/AndroidRuntime(18812): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kodevelop.gndec/com.kodevelop.gndec.LaunchActivity}: java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to android.widget.ListView
11-24 13:16:53.108: E/AndroidRuntime(18812):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
11-24 13:16:53.108: E/AndroidRuntime(18812):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
11-24 13:16:53.108: E/AndroidRuntime(18812):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-24 13:16:53.108: E/AndroidRuntime(18812):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
11-24 13:16:53.108: E/AndroidRuntime(18812):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-24 13:16:53.108: E/AndroidRuntime(18812):    at android.os.Looper.loop(Looper.java:137)
11-24 13:16:53.108: E/AndroidRuntime(18812):    at android.app.ActivityThread.main(ActivityThread.java:5039)
11-24 13:16:53.108: E/AndroidRuntime(18812):    at java.lang.reflect.Method.invokeNative(Native Method)
11-24 13:16:53.108: E/AndroidRuntime(18812):    at java.lang.reflect.Method.invoke(Method.java:511)
11-24 13:16:53.108: E/AndroidRuntime(18812):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-24 13:16:53.108: E/AndroidRuntime(18812):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-24 13:16:53.108: E/AndroidRuntime(18812):    at dalvik.system.NativeStart.main(Native Method)
11-24 13:16:53.108: E/AndroidRuntime(18812): Caused by: java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to android.widget.ListView
11-24 13:16:53.108: E/AndroidRuntime(18812):    at com.kodevelop.gndec.LaunchActivity.onCreate(LaunchActivity.java:42)
11-24 13:16:53.108: E/AndroidRuntime(18812):    at android.app.Activity.performCreate(Activity.java:5104)
11-24 13:16:53.108: E/AndroidRuntime(18812):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
11-24 13:16:53.108: E/AndroidRuntime(18812):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
11-24 13:16:53.108: E/AndroidRuntime(18812):    ... 11 more

I'm willing to share the whole code in zipped format so as to import the project in your system, if need arises.


回答1:


You are trying to get the ID of a framelayout but casting it as listview

DrawerList = (ListView) findViewById(R.id.left_drawer);

which should actually be

DrawerList = (FrameLayout) findViewById(R.id.left_drawer);


来源:https://stackoverflow.com/questions/20175476/load-navigation-drawer-slider-with-dynamic-fragments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!