I'm trying to implement a navigation bar within my android application. However, my compilers complains with following errors:
Error:(39, 25) error: cannot find symbol variable drawer_open
Error:(39, 47) error: cannot find symbol variable drawer_close
My code:
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends ActionBarActivity {
/***********************************************************
MEMBERS
**********************************************************/
private Toolbar m_toolbar;
private String m_navTitles[] = {"Nr. 1", "Nr. 2", "Nr. 3", "Nr. 4" };
private int m_icons[] = {R.drawable.ic_action, R.drawable.ic_action, R.drawable.ic_action, R.drawable.ic_action};
private DrawerLayout m_drawer;
private ActionBarDrawerToggle m_drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Set toolbar */
m_toolbar = (Toolbar) findViewById(R.id.tool_bar); //find toolbar from layout
setSupportActionBar(m_toolbar); //call to set toolbar as the ActionBar
/* Set navigation drawer */
m_drawer = (DrawerLayout) findViewById(R.id.DrawerLayout); //assign drawer object to view
m_drawerToggle = new ActionBarDrawerToggle(this, m_drawer, m_toolbar, R.string.drawer_open, R.string.drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// code here will execute once the drawer is opened
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// Code here will execute once drawer is closed
}
}; // made drawer toggle object
m_drawer.setDrawerListener(m_drawerToggle);
m_drawerToggle.syncState();
}
Please note that my code for the navigation drawer is not finished yet. I wanted to fix the drawer_open/drawer_close errors first.
Many thanks in advance!
Did you have drawer_open and drawer_close in your strings.xml?
I think you didn't add these two strings in your strings.
Try this Your pbm is solved here copy this code and replace yours :
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends ActionBarActivity {
/***********************************************************
MEMBERS
**********************************************************/
private Toolbar m_toolbar;
private String m_navTitles[] = {"Nr. 1", "Nr. 2", "Nr. 3", "Nr. 4" };
private int m_icons[] = {R.drawable.ic_action, R.drawable.ic_action, R.drawable.ic_action, R.drawable.ic_action};
private DrawerLayout m_drawer;
private ActionBarDrawerToggle m_drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Set toolbar */
m_toolbar = (Toolbar) findViewById(R.id.tool_bar); //find toolbar from layout
setSupportActionBar(m_toolbar); //call to set toolbar as the ActionBar
/* Set navigation drawer */
m_drawer = (DrawerLayout) findViewById(R.id.DrawerLayout); //assign drawer object to view
m_drawerToggle = new ActionBarDrawerToggle(this, m_drawer, m_toolbar, "drawer_open", "drawer_close"){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// code here will execute once the drawer is opened
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// Code here will execute once drawer is closed
}
}; // made drawer toggle object
m_drawer.setDrawerListener(m_drawerToggle);
m_drawerToggle.syncState();
}
Related
my app has no error yet it is showing an error "unfortunately zine has stopped"
main activity.java
package piestudio.zine;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends ActionBarActivity{
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUP((DrawerLayout) findViewById(R.id.drawer_layout),toolbar);
}
}
`
navigation drawer activity
package piestudio.zine;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class NavigationDrawerFragment extends Fragment {
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER="user_learned_drawer";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
public NavigationDrawerFragment() {
// Required empty public constructor
}
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer=Boolean.valueOf(readFromPreferences(getActivity(),KEY_USER_LEARNED_DRAWER,"false"));
if(savedInstanceState!=null){
mFromSavedInstanceState=true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
}
public void setUP(DrawerLayout drawerLayout, Toolbar toolbar) {
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
public static void saveToPreferences(Context context, String preferenceName, String preferenceValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferenceName, 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);
}
}
now as you can see the code , now whenever i try to run this on my phone (as my emulator is not working ) it stops by saying ## unfortunatley,zine has stopped
Try changing this code
private Toolbar toolbar;
to this
android.support.v7.widget.Toolbar
and see whether the crash is happening or not. Please logcat output so that we can debug the crash in a better manner.
Due to my lack of knowledge on this I'm jumping from one problem to another. I've been trying to figure it out for hours now and looked through various previous questions but not getting anywhere. Most recent is this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerShadow(int, int)' on a null object reference
at XXXX.NavigationDrawerFragment.setUp(NavigationDrawerFragment.java:136)
at XXXX.EditFactFind.onCreate(EditFactFind.java:72)
at android.app.Activity.performCreate(Activity.java:5990)
My Activity (the main point that it's failing) is:
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
//import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class EditFactFind extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks {
public static final int RESULT_DELETE = -500;
private boolean isInEditMode = true;
private boolean isAddingFactFind = true;
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_factfind);
final Button saveButton = (Button)findViewById(R.id.saveButton);
final Button cancelButton = (Button)findViewById(R.id.cancelButton);
final EditText titleEditText = (EditText)findViewById(R.id.titleEditText);
//final EditText factFindEditText = (EditText)findViewById(R.id.factFindEditText);
final TextView dateTextView = (TextView)findViewById(R.id.dateTextView);
final Button nextButton =(Button) findViewById(R.id.nextButton);
//Create fragment and give it an argument for the selected article
secA_pg1 iniSecFrag = new secA_pg1();
Bundle args = new Bundle();
args.putInt(secA_pg1.ARG_INDEX, 1);
iniSecFrag.setArguments(args);
FragmentTransaction initialTransaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
initialTransaction.replace(R.id.fragment_container, iniSecFrag);
initialTransaction.addToBackStack(null);
//Commit the transaction
initialTransaction.commit();
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
Serializable extra = getIntent().getSerializableExtra("FactFind");
if(extra != null)
{
FactFind factFind = (FactFind) extra;
titleEditText.setText(factFind.getTitle());
// factFindEditText.setText(factFind.getFactFindTitle());
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String date = dateFormat.format(factFind.getDate());
dateTextView.setText(date);
isInEditMode = false;
titleEditText.setEnabled(false);
// factFindEditText.setEnabled(false);
saveButton.setText("Edit");
isAddingFactFind = false;
}
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setResult(RESULT_CANCELED, new Intent());
finish();
}
});
nextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//secA_pg1 secFrag = (secA_pg1) getFragmentManager().findFragmentById(R.id.Sec_A_pg1_fragment);
//Create fragment and give it an argument for the selected article
secA_pg2 newSecFrag = new secA_pg2();
Bundle args = new Bundle();
args.putInt(secA_pg2.ARG_INDEX, 2);
newSecFrag.setArguments(args);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newSecFrag);
transaction.addToBackStack(null);
//Commit the transaction
transaction.commit();
}
});
saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(isInEditMode)
{
Intent returnIntent = new Intent();
FactFind factFind = new FactFind(titleEditText.getText().toString(),Calendar.getInstance().getTime());
returnIntent.putExtra("FactFind", factFind);
setResult(RESULT_OK, returnIntent);
finish();
}
else
{
isInEditMode = true;
saveButton.setText("Save");
titleEditText.setEnabled(true);
// factFindEditText.setEnabled(true);
}
}
});
}
and my Navigation drawer is failing at the setUp method:
package XXXX;
import android.support.v4.app.FragmentActivity;
import android.app.ActionBar;
//import android.support.v7.app.ActionBar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.support.v7.widget.Toolbar;
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
// mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
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;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
// getActivity().InvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
XML of the drawer is
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="XXXX.MainActivity">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/container"
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.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment
android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="XXXX.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.DrawerLayout>
I'm assuming that mDrawerLayout isn't being picked up correctly and is therefore returning null but I can't figure out why that is.
Thanks.
I am following the tutorial on http://developer.android.com/training/implementing-navigation/nav-drawer.html and am having problems with the ActionBarDrawerToggle. The documentation uses v4, but since that's deprecated I am trying to use the v7.
My problem is that I can not get a drawer/hamburger icon to show, but it always shows the up arrow, even when I am on the main activty that has no parents in the manifest.
This is my main activity:
import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.example.R;
public class MainActivity extends Activity
{
private static final String LOG_TAG = MainActivity.class.getName();
private String[] menuItems;
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
menuItems = getResources().getStringArray(R.array.menu_items);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.menu);
drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.menu_list_item, menuItems));
drawerList.setOnItemClickListener(new DrawerItemClickListener());
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
LoginFragment loginFragment = new LoginFragment();
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, loginFragment).commit();
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectMenuItem(int position)
{
Fragment fragment = null;
switch (position) {
case 0:
fragment = new DialFragment();
break;
case 1:
fragment = new NumbersFragment();
break;
case 2:
fragment = new LoginFragment();
break;
}
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
drawerList.setItemChecked(position, true);
drawerLayout.closeDrawer(drawerList);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener
{
#Override
public void onItemClick(AdapterView parent, View view, int position, long id)
{
selectMenuItem(position);
}
}
}
It works when I change:
import android.support.v7.app.ActionBarDrawerToggle;
to
import android.support.v4.app.ActionBarDrawerToggle;
and when I change:
drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.string.drawer_open,
R.string.drawer_close
)
to
drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
)
After these changes I can see a correct hamburger icon that collapses/expands when the drawer is opened/closed, but I'd like to get the v7 to work. Any ideas?
Edit: just tried it on my phone (running the Android 5.0.1) and this shows the hamburger icon when the drawer is closed and animates into an arrow when opened. The emulator which I am using is API 15 / Android 4.0.3
as ActionBarDrawerToggle has two different Signature but with the same name for constructor , and you used the constructor with 4 parameter
drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.string.drawer_open,
R.string.drawer_close
)
to solve that issue you could use the constructor method which accept toolbar
drawerToggle = new ActionBarDrawerToggle(
this,yourtoolbar
drawerLayout,
R.string.drawer_open,
R.string.drawer_close
)
I want to set toggle button icon to right in my android app. here is my code. how I can do it?By the way I set the value of android:layout_gravity to right and now I want to set the Drawer's icon to right, too. How I can do this?
My MainActivity's class code:
package com.examplde.menuefinal;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
String dokme_txt= "Esfandune";
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mPlanetTitles = getResources().getStringArray(R.array.dokmeha);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mPlanetTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int post, long arg3) {
String dokme_txt = getResources().getStringArray(R.array.dokmeha)[post];
Toast.makeText(getBaseContext(),"برروی "+dokme_txt+" کلیک شد", Toast.LENGTH_SHORT).show();
mDrawerLayout.closeDrawer(mDrawerList);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_launcher, R.string.drawer_open,
R.string.drawer_close) {
#Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(dokme_txt);
supportInvalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("تنظیمات");
supportInvalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
// tanzim e drawer toggle be surate DrawerListener baraye mDrawerLayout
// emun
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can do this by following code, but min level API IS 17.
add this to your manifest application and activity tags
android:supportsRtl="true"
then after setContentView in mainActivity, add following. to make your hamburger icon on right side.
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
I'm trying to let my HomeActivity extend BaseActivity (as suggested here) so I can have the same Navigation Drawer in every Activity I want. But I get a NullPointerException in the onCreate method of my HomeActivity. This is the code of BaseActivity:
import android.os.Bundle;
import android.app.Activity;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class BaseActivity extends Activity
{
public DrawerLayout drawerLayout;
public ListView drawerList;
private String[] drawerListEntries;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState)
{
drawerListEntries = new String[] {"Bla bla", "Profile", "Home"};
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle((Activity) this, drawerLayout, R.drawable.ic_navigation_drawer, 0, 0)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(R.string.app_name);
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(R.string.hello_world);
}
};
drawerLayout.setDrawerListener(drawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
//layers = getResources().getStringArray(R.array.layers_array);
drawerList = (ListView) findViewById(R.id.drawer_list);
// View header = getLayoutInflater().inflate(R.layout.drawer_list_header, null);
// drawerList.addHeaderView(header, null, false);
drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, drawerListEntries));
// View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
// R.layout.drawer_list_footer, null, false);
// drawerList.addFooterView(footerView);
drawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
//map.drawerClickEvent(pos);
String selectedValue = (String) drawerList.getAdapter().getItem(pos);
Toast.makeText(getBaseContext(), selectedValue, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
And this is the code of HomeActivity which extends BaseActivity:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.facebook.Session;
public class HomeActivity extends BaseActivity {
TextView greeting;
Button orderButton, deliverButton, logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
//return super.onCreateOptionsMenu(menu);
return true;
}
}
I get a NullPointerException in:
super.onCreate(savedInstanceState); // HomeActivity
and when I click on that, it goes to:
drawerLayout.setDrawerListener(drawerToggle); // BaseActivity
Does anyone know how I can fix this?
Update:
drawer_list.xml:
<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" >
<ListView
android:id="#+id/drawer_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp"
android:background="#android:color/transparent"
android:cacheColorHint="#android:color/transparent"
android:divider="#CCCCCC"
android:dividerHeight="1dp"
android:paddingLeft="2dp" />
</android.support.v4.widget.DrawerLayout>
and drawer_list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/drawer_list_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="12dp"
android:textSize="24sp"
android:layout_gravity="left"
android:textColor="#color/belize_hole"
android:fontFamily="sans-serif-light">
</TextView>
</LinearLayout>
Same issue in a few posts. I am new to android but solved it this way. Would love to hear if there is a better "right" way to do it. (yes, without fragments but I know I need to learn them eventually).
The problem appears that the base class is not aware of the layout. Not sure how or why it worked for others without having to do something like this.. but I am new to Android.
I was getting the same error and solved by passing my layout to the base via onCreate.
So in the base, I modified onCreate to be like this:
protected void onCreate(Bundle savedInstanceState, int resLayoutID)
{
super.onCreate(savedInstanceState);
setContentView(resLayoutID);
Then, from my new activity, I have this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.my_activity);
This code in my base now works instead of staying null:
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.left_drawer);
btw, this result was suggested to me by a friend and it worked for me.