Problems trying to open the Navigationdrawer with the Home Button on the Toolbar

Asked

Viewed 479 times

2

I’m trying to open the Navigationdrawer of my application in my Main Activity through the home button available on Toolbar when using Actionbardrawertoggle, but when pressing the button my application stops working.

Image referring to the home button and the Navigationdrawer:

https://www.filepicker.io/api/file/ZPSptlSVm1q929U44dwg

I don’t know if the problem is in the Navigationdrawer but you can only open it by sliding your finger on the left side of the device. As said before while using button to open it occurs error posted below.

Error found:

java.lang.IllegalArgumentException: No drawer view found with gravity LEFT
        at android.support.v4.widget.DrawerLayout.openDrawer(DrawerLayout.java:1322)
        at android.support.v7.app.ActionBarDrawerToggle.toggle(ActionBarDrawerToggle.java:289)
        at android.support.v7.app.ActionBarDrawerToggle.access$100(ActionBarDrawerToggle.java:65)
        at android.support.v7.app.ActionBarDrawerToggle$1.onClick(ActionBarDrawerToggle.java:201)
        at android.view.View.performClick(View.java:4785)
        at android.view.View$PerformClick.run(View.java:19884)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5343)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

Navigationdrawer fragment xml file:

<LinearLayout
    android: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"/>

Xml file from main Activity:

<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);
}

}

Java file from Navigationdrawer:

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);

}
}

File build.Radle:

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'
}
  • Could you put your build.gradle? At first it should be a version bug, if it is not the last, recommend updating the library appcompat v7.

1 answer

3


  • 1

    Actually using Navigationview is much easier and does not have the bug on account of Actionbardrawertoggle.

  • I’m glad I helped. There are many other cool components in this example that I passed.

  • The only thing that weighed me was that I can’t use (at least I don’t know how) a Recyclerview in Navigationview, just to add a Header and a menu.

  • I don’t quite understand. What else would you like to add?

  • I wanted to add a Recyclerview to the Navigationdrawer using Navigationview.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.