Can't add navigation icon to activity - java

public void setContentView(int layoutResID)
{
DrawerLayout fullView = (DrawerLayout) getLayoutInflater().inflate(R.layout.activity_base, null);
FrameLayout activityContainer = (FrameLayout) fullView.findViewById(R.id.activity_content);
getLayoutInflater().inflate(layoutResID, activityContainer, true);
super.setContentView(fullView);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
{
actionBar.setDisplayHomeAsUpEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close)
{
public void onDrawerClosed(View view)
{
supportInvalidateOptionsMenu();
//drawerOpened = false;
}
public void onDrawerOpened(View drawerView)
{
supportInvalidateOptionsMenu();
//drawerOpened = true;
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
drawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
}
}
I want to add navigation drawer icon to this navigation drawer activity. now i have edited code but still now error app stops at startup

maybe you can try to add it to layout file modifying the xml code,or follow this tutorial for more information Android Sliding Menu

Related

Adding navigation drawer from second activity to activity_main. Using .opendrawer in main activity to open second

I have created a project int activity_main and want to add a Navigation drawer to it.
I have gone into the java folder. Right click > new > Actvity > Navigation Drawer activity.
Note: I DON't have an action bar, to create the menu button(3 stacked lines)
Now I don't know how to actually open the navigation drawer over activity_main, without the app crashing.
Thanks.
I've tried doing an on click listener with a button which has
the drawer layout defined as dl (DrawerLayout dl = (DrawerLayout)findviewbyIOd(R.id.Drawer_layout))
and have done
dl.openDrawer(Gravity.LEFT);
have tried putting the code from the NavDrawer activity into the activity_main, but app won't start.
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
Switch OnOff;
EditText editText;
int NumberPicked;
int NumberPicked2;
private DrawerLayout dl;
private ActionBarDrawerToggle abdt;
Values[] troughvals = new Values[8];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BobbleSelector BS = new BobbleSelector();
final DrawerLayout dl = (DrawerLayout)findViewById(R.id.dl);
Button btnChange = (Button) findViewById(R.id.btnChange);
Switch OnOff = (Switch) findViewById(R.id.OnOff);
NumberPicker numberPicker2 = findViewById(R.id.numberPicker2);
NumberPicker numberPicker = findViewById(R.id.numberPicker);
numberPicker.setMinValue(00);
numberPicker2.setMinValue(00);
numberPicker2.setMaxValue(23);
numberPicker.setMaxValue(23);
btnChange.setOnClickListener( new View.OnClickListener(){
public void onClick(View v){
dl.openDrawer(Gravity.LEFT);
}
});
OnOff.setTextOff("On");
OnOff.setTextOn("Off");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return abdt.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
public void handleSwitchClick(View view) {
Switch s = (Switch) view;
boolean isChecked = s.isChecked();
}
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked){
switch (compoundButton.getId()){
case R.id.OnOff:
break;
}
}
}
Note: have disabled fab, because it could not be found in my project.
I have created a custom Menu for the Navigation Drawer
public class BobbleSelector extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bobble_selector);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Button fab = findViewById(R.id.btnChange);
// fab.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
DrawerLayout drawer = findViewById(R.id.dl);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.dl);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bobble_selector, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = findViewById(R.id.dl);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Drawer Layout
<?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/dl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_bobble_selector"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_bobble_selector"
app:menu="#menu/nav_menu" />
</android.support.v4.widget.DrawerLayout>
From Logcat
2019-06-02 13:13:08.195 12745-12745/com.example.mytest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mytest, PID: 12745
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.openDrawer(int)' on a null object reference
at com.example.mytest.MainActivity$1.onClick(MainActivity.java:49)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Expected to open drawer with the changebutton.openDrawer(Gravity.Left) But crashes the app.
Found I needed to move the code relating to the nav bar to the bottom of OnCreate and set the "SetContentView()" to be the layout for the Navigation bar.
Then it worked perfectly.
Before
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btnChange);
drawer = findViewById(R.id.dl);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer, R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//Not nav
Switch OnOff = (Switch) findViewById(R.id.OnOff);
NumberPicker numberPicker2 = findViewById(R.id.numberPicker2);
NumberPicker numberPicker = findViewById(R.id.numberPicker);
numberPicker.setMinValue(00);
numberPicker2.setMinValue(00);
numberPicker2.setMaxValue(23);
numberPicker.setMaxValue(23);
OnOff.setTextOff("On");
OnOff.setTextOn("Off");
//not nav
}
After
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btnChange);
//Not nav
Switch OnOff = (Switch) findViewById(R.id.OnOff);
NumberPicker numberPicker2 = findViewById(R.id.numberPicker2);
NumberPicker numberPicker = findViewById(R.id.numberPicker);
numberPicker.setMinValue(00);
numberPicker2.setMinValue(00);
numberPicker2.setMaxValue(23);
numberPicker.setMaxValue(23);
OnOff.setTextOff("On");
OnOff.setTextOn("Off");
//not nav
setContentView(R.layout.activity_bobble_selector);
drawer = findViewById(R.id.dl);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer, R.string.navigation_drawer_open,R.string.navigation_drawer_close);
assert drawer != null;
drawer.addDrawerListener(toggle);
toggle.syncState();
}

ActionBarDrawerToggle without custom toolbar

I want to use ActionBarDrawerToggle without having custom toolbar instead using current actionBar
my code goes as follow :
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.grid);
ActionBarDrawerToggle mToogle = new ActionBarDrawerToggle(this, drawerLayout, actionbar, R.string.app_name, R.string.app_name);
I know I should use :
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
and use toolBar instead of action bar in ActionBarDrawerToggle but can I use ActionBarDrawerToggle without having new toolbar.
Error I get :
error: incompatible types: ActionBar cannot be converted to Toolbar
Solved that by removing actionBar my code now goes like this :
ActionBarDrawerToggle mToogle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.grid, R.drawable.contact) {
#Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
// creates call to onPrepareOptionsMenu()
}
};

ActionBar Back button opens drawer instead of going back

In my app I have problem like this. Note that I'm working with fragments and I have drawer too.
That's the method in my MainActivity for drawer open/close.
public void drawerInit() {
toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer);
view = findViewById(R.id.mainView);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
float moveFactor = (drawerView.getWidth() * slideOffset);
view.setTranslationX(moveFactor);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
drawer.addDrawerListener(toggle);
toggle.syncState();
}
Example I have 3 fragments (F1, F2, F3). F1 is my main fragment where I can open and close the drawer. When I'm opening F2 or F3 fragments, I need to change the drawer icon to back arrow. I'm doing this part successfully, but the problem is when I'm clicking on this back arrow, that opens the navigation drawer instead of going back. So how can I fix this part?
Here the part, where I'm changing the icon to back arrow in fragment.
((AppCompatActivity) getActivity()).getSupportActionBar().show();
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity) getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
Add in your Activity
public void crateMenuButton(){
toggle.setDrawerIndicatorEnabled(true);
if(toolbarDrawable == null) {
toolbarDrawable = toolbar.getNavigationIcon();
}
toolbar.setNavigationIcon(toolbarDrawable);
invalidateOptionsMenu();
toggle.syncState();
}
public void createBackButton() {
toggle.setDrawerIndicatorEnabled(false);
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if the drawerToggle is disabled, fall off to the home button action
if (!toggle.isDrawerIndicatorEnabled()) {
// pop fragment here
FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack();
}
} else {
if (drawerLayout.isDrawerOpen(navigationView)) {
drawerLayout.closeDrawer(navigationView);
} else {
drawerLayout.openDrawer(navigationView);
}
}
}
});
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white));
}
Download Back Arrow
Then call from your fragment as your need
((YourActivity) getActivity()).createBackButton();
OR
((YourActivity) getActivity()).crateMenuButton();

Hamburger doesn't work

I managed to create a drawer and have the hamburger sign but the hamburger is not working when tapped. Also how can I change the code so that my app has a transparent notification bar so that the color is same(or preferably a little darker) and one can see the app drawer opened in status bar. Something like this: Transparent status bar
FirstActivity.java:
public class FirstActivity extends AppCompatActivity {
DrawerLayout mDrawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_me_clicked);
Toolbar toolbar= (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false); //removes the package name from toolbar
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// Window w = getWindow(); // in Activity's onCreate() for instance //Integration of app into status bar
// w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
// }
// These lines are needed to display the top-left hamburger button
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Make the hamburger button work
mDrawer = (DrawerLayout) findViewById(R.id.DL);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,mDrawer,R.string.app_name,R.string.app_name){
#Override
public void onDrawerClosed(View drawerView) {
}
#Override
public void onDrawerOpened(View drawerView) {
}
};
mDrawer.addDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
// toasts the message when ListView item is clicked
ListView mDrawerListView = (ListView) findViewById(R.id.left_drawer);
mDrawerListView.setOnItemClickListener(new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String drawerstring = ("Menu Item at position " + position + " clicked.");
mDrawer.closeDrawer(GravityCompat.START);
Toast.makeText(getApplicationContext(),drawerstring,Toast.LENGTH_SHORT).show();
}
});
}
You have to override onOptionsItemSelected and handle the home item to open the drawer. Its not done for you, because Android doesn't know what you're using that button for (home? back? hamburger? Something else?). The ActionDrawerToggle knows how to handle it if you want to just delegate it.

Android : Unable to integrate Drawer navigation because already calling extends for Google-Maps

I am working on an Android project in which I would like to add Drawer functionality, for which I already have classes and all ready.
THe problem is the Drawer code works by extends or extending the class which wants to add a drawer, and similarly my GoogleMaps code works in the same way. But because of Multiple-inheritance, I cannot extend 2 classes.
What should I do?
Google-maps code :
public class MapsActivity extends FragmentActivity {
GoogleMap googleMap;
SharedPreferences sharedPreferences;
int locationCount = 0;
private RestaurantServiceImpl restaurantService = new RestaurantServiceImpl();
List<RestRestaurant> restRestaurantList = new ArrayList<>();
GPSTracker gps;
double longitude, latitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapsact);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Opening the sharedPreferences object
sharedPreferences = getSharedPreferences("location", 0);
// Getting number of locations already stored
locationCount = sharedPreferences.getInt("locationCount", 0);
// Getting stored zoom level if exists else return 0
String zoom = sharedPreferences.getString("zoom", "12");
gps = new GPSTracker(MapsActivity.this);
if (gps.canGetLocation()) {
longitude = gps.getLongitude();
latitude = gps.getLatitude();
restRestaurantList = this.restaurantService.getRestaurantsByLocation(longitude,latitude);
double lat=0, longi=0;
for(RestRestaurant restRestaurant : restRestaurantList){
drawMarker(new LatLng(restRestaurant.getLatitude(),restRestaurant.getLongitude()), restRestaurant.getRestaurantName(), restRestaurant.getRestaurantId());
lat = restRestaurant.getLatitude();
longi = restRestaurant.getLongitude();
}
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(lat,longi)));
// Setting the zoom level in the map on last position is clicked
googleMap.animateCamera(CameraUpdateFactory.zoomTo(Float.parseFloat(zoom)));
} else {
gps.showSettingsAlert();
}
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
int restoId = Integer.valueOf(marker.getSnippet());
Intent intent = new Intent(MapsActivity.this, MenuCardList.class);
intent.putExtra("restaurantid", restoId);
startActivity(intent);
finish();
return true;
}
});
}
This class I need to extend to add a drawer :
public class DrawerLoader extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
private ArrayList<DrawerModel> navDrawerItems;
private DrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawerlayout);
}
public void set(String[] navMenuTitles, TypedArray navMenuIcons) {
mTitle = mDrawerTitle = getTitle();
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<DrawerModel>();
If any more information is required, kindly let me know.
Ignoring all your work regarding a navigation drawer, this would be my preferred solution, since There is no need for a extra Fragment, List filling, new classes....
1, Create a nav_menu.xml (in menues folder):
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group
android:checkableBehavior="single">
<item
android:id="#+id/drawer_home"
android:checked="true"
android:icon="#drawable/ic_home_black_24dp"
android:title="Home"/>
<item
android:id="#+id/drawer_favourite"
android:icon="#drawable/ic_favorite_black_24dp"
android:title="Favourites"/>
<item
android:id="#+id/drawer_settings"
android:icon="#drawable/ic_settings_black_24dp"
android:title="Settings"/>
</group>
2, Wrap your activites layout with a DrawerLayout:
<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">
<!-- Your activity layout here-->
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/nav_menu"/>
</android.support.v4.widget.DrawerLayout>
3, Update your activities java code:
//If you have a toolbar (recommended!)
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
//and finally the Navigation View Code:
final NavigationView navigation = (NavigationView) findViewById(R.id.navigation);
navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
navigation.setCheckedItem(menuItem.getItemId());
drawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.drawer_home:
//open fragment home
return true;
case R.id.drawer_favourite:
//open fragment favourite
return true;
case R.id.nav_drawer_channels:
showFragment(2);
return true;
case R.id.drawer_settings:
//open settings
return true;
}
return false;
}
});
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
toolbar,
R.string.drawer_open, //simply a String "open"
R.string.drawer_close) { //simply a String "close"
public void onDrawerClosed(View view) {
super.onDrawerOpened(drawerLayout);
drawerToggle.syncState();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerClosed(drawerLayout);
drawerToggle.syncState();
}
};
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
//And, last but not least, open the drawer with a Click on 'home'
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
And you are done! No messing with extra fragment, unnecessary and messy code.

Categories