Problems trying to open NavigationDrawer with the Home Button in ToolBar

2

I'm trying to open the NavigationDrawer of my application in my Main Activity via the home button available on the toolbar when using ActionBarDrawerToggle, but when I press the button my application stops working.

Image for home button and NavigationDrawer:

IdonotknowiftheproblemisinNavigationDrawerbutyoucanonlyopenitbyslidingyourfingerontheleftsideofthedevice.Assaidbeforewhenusingthebuttontoopenitoccurstheerrorpostedbelow.

Errorencountered:

java.lang.IllegalArgumentException:NodrawerviewfoundwithgravityLEFTatandroid.support.v4.widget.DrawerLayout.openDrawer(DrawerLayout.java:1322)atandroid.support.v7.app.ActionBarDrawerToggle.toggle(ActionBarDrawerToggle.java:289)atandroid.support.v7.app.ActionBarDrawerToggle.access$100(ActionBarDrawerToggle.java:65)atandroid.support.v7.app.ActionBarDrawerToggle$1.onClick(ActionBarDrawerToggle.java:201)atandroid.view.View.performClick(View.java:4785)atandroid.view.View$PerformClick.run(View.java:19884)atandroid.os.Handler.handleCallback(Handler.java:739)atandroid.os.Handler.dispatchMessage(Handler.java:95)atandroid.os.Looper.loop(Looper.java:135)atandroid.app.ActivityThread.main(ActivityThread.java:5343)atjava.lang.reflect.Method.invoke(NativeMethod)atjava.lang.reflect.Method.invoke(Method.java:372)atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)atcom.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

NavigationDrawerfragmentxmlfile:

<LinearLayoutandroid:id="@+id/containerDrawerImage"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@drawable/fundo_navigation_drawer"
    android:layout_marginBottom="70dp">

    <com.facebook.login.widget.ProfilePictureView
        android:id="@+id/picture_drawer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="7dp"
        android:layout_marginTop="30dp"/>

    <TextView
        android:id="@+id/text_drawer_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18dp"
        android:hint="User name"
        android:layout_marginLeft="7dp"
        android:layout_marginTop="3dp"
        android:textColor="#ffffffff" />

    <TextView
        android:id="@+id/text_drawer_score"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18dp"
        android:hint="User Score"
        android:layout_marginLeft="7dp"
        android:layout_marginTop="7dp"
        android:textColor="#ffffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ranking"
        android:layout_marginTop="7dp"
        android:layout_gravity="center"
        android:textSize="20sp"
        android:textStyle="bold" />

</LinearLayout>

<android.support.v7.widget.RecyclerView
    android:id="@+id/drawerList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="240dp"
    android:padding="7dp"/>

Main activity xml file:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="fexus.com.br.perguntasc.activitys.MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"/>

    <fexus.com.br.perguntasc.extras.SlidingTabLayout
        android:id="@+id/stl_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <android.support.v4.view.ViewPager
        android:id="@+id/vp_tabs"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

<fragment
    android:id="@+id/fragment_navigation_drawer"
    android:name="fexus.com.br.perguntasc.navigationdrawer.NavigationDrawerFragment"
    android:layout_width="280dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    tools:layout="@layout/fragment_navigation_drawer" />

MainActivity java file:

package fexus.com.br.perguntasc.activitys;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.facebook.FacebookSdk;

import fexus.com.br.perguntasc.R;
import fexus.com.br.perguntasc.adapters.TabsAdapter;
import fexus.com.br.perguntasc.extras.SlidingTabLayout;
import fexus.com.br.perguntasc.fragments.LoginFragment;
import fexus.com.br.perguntasc.navigationdrawer.NavigationDrawerFragment;


public class MainActivity extends AppCompatActivity implements                            NavigationDrawerFragment.NavigationDrawerCallbacks {

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

    FacebookSdk.sdkInitialize(this);

    setContentView(R.layout.activity_main);

    String userName = LoginFragment.userName;
    String userId = LoginFragment.userId;

    //TOOLBAR
    Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
    if(mToolbar != null) {
        mToolbar.setTitle("PerguntASC");
        setSupportActionBar(mToolbar);
    }

    NavigationDrawerFragment mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);

    DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.fragment_navigation_drawer);

    if(drawerLayout == null) {
        Log.e("FEXUS", "drawerLayout equals NULL - onCreate - MAIN ACTIVITY");
    }

    mNavigationDrawerFragment.setUp(R.id.fragment_navigation_drawer, drawerLayout, mToolbar, userName, userId);


    //TABS
    ViewPager mViewPager = (ViewPager) findViewById(R.id.vp_tabs);
    mViewPager.setAdapter(new TabsAdapter(getSupportFragmentManager(), this));

    SlidingTabLayout mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.stl_tabs);
    mSlidingTabLayout.setDistributeEvenly(true);
    mSlidingTabLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
    mSlidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.colorAccent));
    mSlidingTabLayout.setViewPager(mViewPager); //all proprieties must be before set view pager

}


@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) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    switch (id) {
        case R.id.action_settings:
            break;
    }

    return super.onOptionsItemSelected(item);
}

}

NavigationDrawer java file:

package fexus.com.br.perguntasc.navigationdrawer;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.login.widget.ProfilePictureView;

import java.util.ArrayList;
import java.util.List;

import fexus.com.br.perguntasc.R;
import fexus.com.br.perguntasc.adapters.RecyclerViewAdapter;
import fexus.com.br.perguntasc.extras.Information;

public class NavigationDrawerFragment extends Fragment {

/**
 * Remember the position of the selected item.
 */
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

/**
 * Per the design guidelines, you should show the drawer on launch until the user manually
 * expands it. This shared preference tracks this.
 */
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";

private static final String PREF_FILE_NAME = "testpref";

/**
 * Helper component that ties the action bar to the navigation drawer.
 */
private ActionBarDrawerToggle mDrawerToggle;

private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
private DrawerLayout mDrawerLayout;

public NavigationDrawerFragment() {
}

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

    mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), PREF_USER_LEARNED_DRAWER, "false"));
    if(savedInstanceState != null) {
        mFromSavedInstanceState = true;
    }
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // Indicate that this fragment would like to influence the set of actions in the action bar.
    setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);

    RecyclerView recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);

    RecyclerViewAdapter adapter = new RecyclerViewAdapter(getActivity(), getData());

    recyclerView.setAdapter(adapter);

    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    return layout;
}

public static List<Information> getData() {
    List<Information> data = new ArrayList<>();
    String[] profilePicturesId = { "777637332331539", "892473870815110", "0", "0", "0" };
    String[] names = { "Pessoa 1", "Pessoa 2", "Pessoa 3", "Pessoa 4", "Pessoa 5" };
    String[] scores = { "500", "400", "300", "200", "100" };
    for(int i=0; i < names.length && i < scores.length && i < profilePicturesId.length; i++) {
        Information current = new Information();
        current.name = names[i];
        current.score = scores[i];
        current.profilePictureId = profilePicturesId[i];
        data.add(current);
    }
    return data;
}


/**
 * Users of this fragment must call this method to set up the navigation drawer interactions.
 *
 * @param drawerLayout The DrawerLayout containing this fragment's UI.
 */
public void setUp(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar, String name, String id) {

    View containerView = getActivity().findViewById(fragmentId);

    ProfilePictureView picture_drawer = (ProfilePictureView) getActivity().findViewById(R.id.picture_drawer);
    picture_drawer.setProfileId(id);

    TextView text_drawer_name = (TextView) getActivity().findViewById(R.id.text_drawer_name);
    text_drawer_name.setText(name);

    TextView text_drawer_score = (TextView) getActivity().findViewById(R.id.text_drawer_score);
    text_drawer_score.setText("Your Score: 500  " + id);

    mDrawerLayout = drawerLayout;

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

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the navigation drawer and the action bar app icon.
    mDrawerToggle = new ActionBarDrawerToggle(
            getActivity(),                    /* host Activity */
            drawerLayout,                    /* DrawerLayout object */
            toolbar,
            R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
            R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
    ) {
        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            if (!isAdded()) {
                return;
            }

            getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            if (!isAdded()) {
                return;
            }

            if (!mUserLearnedDrawer) {
                // The user manually opened the drawer; store this flag to prevent auto-showing
                // the navigation drawer automatically in the future.
                mUserLearnedDrawer = true;
                saveToPreferences(getActivity(), true);
            }

            getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }


    };

    if(!mUserLearnedDrawer && !mFromSavedInstanceState) {
        drawerLayout.openDrawer(containerView);
    }

    drawerLayout.setDrawerListener(mDrawerToggle);

    // Defer code dependent on restoration of previous instance state.
    drawerLayout.post(new Runnable() {
        @Override
        public void run() {
            mDrawerToggle.syncState();
        }
    });

}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}

@Override
public void onDetach() {
    super.onDetach();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    int mCurrentSelectedPosition = 0;
    outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Forward the new configuration the drawer toggle component.
    mDrawerToggle.onConfigurationChanged(newConfig);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }

    if (item.getItemId() == R.id.action_example) {
        Toast.makeText(getActivity().getApplicationContext(), "Example action.", Toast.LENGTH_SHORT).show();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * Callbacks interface that all activities using this fragment must implement.
 */
public interface NavigationDrawerCallbacks {
}

public static void saveToPreferences(Context context, boolean preferenceValue) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(PREF_USER_LEARNED_DRAWER, preferenceValue);
    editor.apply();
}

public static String readFromPreferences(Context context, String preferenceName, String defaultValue) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
    return sharedPreferences.getString(preferenceName, defaultValue);

}
}

Build.gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    repositories {
        mavenCentral()
    }

    defaultConfig {
        applicationId "fexus.com.br.perguntasc"
        minSdkVersion 14
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),    'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:recyclerview-v7:22.1.1'
    compile 'com.facebook.android:facebook-android-sdk:4.2.0'
}
    
asked by anonymous 30.07.2015 / 18:34

1 answer

3

Try using the NavigationView component of the new Material Design support library. It is simpler and will still solve your problem.

Follow this example:

link

Hug.

    
01.08.2015 / 21:06