I am creating a application which contains Navigation Drawer Activity. I am loading different Fragments in my main Screen. Now when I have to call Fragment at that time it works fine but when I want to call some sort of service like call, image picker at that time I added setNavigationItemSelectedListener which is works fine but all other fragments are not loading now.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow, R.id.nav_franchise,
R.id.nav_tieUP, R.id.nav_giftVoucher, R.id.nav_faq, R.id.nav_privacy_policy,
R.id.nav_tools, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
if (id == R.id.callUs) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + "XXXxxxXXX"));
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE},REQUEST_PHONE_CALL);
}
else
{
startActivity(intent);
}
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
}
When you call NavigationUI.setupWithNavController(navigationView, navController), you're saying that you want NavController to handle click events from your NavigationView, navigating to the related screen as per the NavigationUI documentation. This, by necessity, calls setNavigationItemSelectedListener() internally.
By calling setNavigationItemSelectedListener afterwards, you remove the original listener, which is why your other items don't do anything anymore. You can trigger the default behavior by calling NavigationUI.onNavDestinationSelected()
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
if (id == R.id.callUs) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + "XXXxxxXXX"));
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE},REQUEST_PHONE_CALL);
}
else
{
startActivity(intent);
}
}
else
{
// Make your navController object final above
// or call Navigation.findNavController() again here
NavigationUI.onNavDestinationSelected(menuItem, navController);
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
I tried to make a fragment and made a drawer here is my code:
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.content.res.Configuration;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.NavigationView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, NavigationView.OnNavigationItemSelectedListener{
private Toolbar mToolBar;
private NavigationView mDrawer;
private ActionBarDrawerToggle mdrawerToggle;
private DrawerLayout mDrawerLayout;
private RelativeLayout digitalFrontier;
private RelativeLayout forwardThinkers;
private RelativeLayout preferedActions;
private LinearLayout innerParent;
public String viewVar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
digitalFrontier.setOnClickListener(this);
forwardThinkers.setOnClickListener(this);
preferedActions.setOnClickListener(this);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mdrawerToggle.onConfigurationChanged(newConfig);
}
private void initViews(){
mToolBar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mToolBar);
mDrawer = (NavigationView) findViewById(R.id.main_drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_parent);
mdrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
mToolBar,
R.string.drawer_open,
R.string.drawer_close);
mDrawerLayout.setDrawerListener(mdrawerToggle);
// indicator based on whether the drawerlayout is in open or closed
mdrawerToggle.syncState();
digitalFrontier = (RelativeLayout) findViewById(R.id.digital_frontier);
forwardThinkers = (RelativeLayout) findViewById(R.id.forward_thinkers);
preferedActions = (RelativeLayout) findViewById(R.id.prefered_actions);
innerParent = (LinearLayout) findViewById(R.id.inner_parent);
mDrawer.setNavigationItemSelectedListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.digital_frontier || v.getId() == R.id.forward_thinkers ||
v.getId() == R.id.prefered_actions ){
detailActivity(v);
}
}
private void detailActivity(View view){
switch (view.getId()){
case R.id.digital_frontier:
viewVar = "digital frontier";
break;
case R.id.forward_thinkers:
viewVar = "forward thinkers";
break;
case R.id.prefered_actions:
viewVar = "prefered actions";
break;
}
Snackbar.make(mDrawerLayout, viewVar , Snackbar.LENGTH_LONG).show();
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return false;
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the planet to show based on
// position
Fragment fragment = null;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.agency_menu_item:
fragmentClass = FragmentAgency.class;
break;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = this.getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_content,
fragment).commit();
// Highlight the selected item, update the title, and close the drawer
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
//mDrawer.closeDrawers();
}
Related
I would like to implement the sign out method in my project. i watch all youtube tutorial but seems like the navigation drawer is the update version. and i'm clueless on how to implement those sign out coding into my coding.
the newest version of the navigation drawer already built in with the ui package folder. So i'm not quite sure on how to implement those tutorial code because most of the tutorial code have this code.
below is the tutorial code and i don't know on how to implement the sign out method into my home.java code. thank you
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
getSupportActionBar().setTitle("Home");
getSupportFragmentManager().beginTransaction().replace(R.id.container,new HomeFragment()).commit();
} else if (id == R.id.nav_profile) {
getSupportActionBar().setTitle("Profile");
getSupportFragmentManager().beginTransaction().replace(R.id.container,new ProfileFragment()).commit();
} else if (id == R.id.nav_settings) {
getSupportActionBar().setTitle("Settings");
getSupportFragmentManager().beginTransaction().replace(R.id.container,new SettingsFragment()).commit();
}
else if (id == R.id.nav_signout) {
FirebaseAuth.getInstance().signOut();
Intent loginActivity = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(loginActivity);
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
this is my home.java code
package com.example.guru;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.widget.TextView;
public class Home extends AppCompatActivity {
FirebaseAuth firebaseAuth;
FirebaseUser currentUser;
DatabaseReference databaseReference;
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//ini
firebaseAuth = FirebaseAuth.getInstance();
currentUser = firebaseAuth.getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference("Customer");
FloatingActionButton fab = findViewById(R.id.fab);
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.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_profile, R.id.nav_orders,R.id.nav_logout)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
updateNavHeader();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public void updateNavHeader() {
NavigationView navigationView = findViewById(R.id.nav_view);
View headerView= navigationView.getHeaderView(0);
TextView navName= headerView.findViewById(R.id.txtName);
TextView navEmail=headerView.findViewById(R.id.txtEmail);
navName.setText(currentUser.getDisplayName());
navEmail.setText(currentUser.getEmail());
}
}
LogoutFragment
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.example.guru.R;
public class LogoutFragment extends Fragment {
private LogoutViewModel logoutViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
logoutViewModel =
ViewModelProviders.of(this).get(LogoutViewModel.class);
View root = inflater.inflate(R.layout.fragment_logout, container, false);
final TextView textView = root.findViewById(R.id.text_logout);
logoutViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
and this is my LogoutViewModel
package com.example.guru.ui.Logout;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class LogoutViewModel extends ViewModel {
private MutableLiveData<String> mText;
public LogoutViewModel() {
mText = new MutableLiveData<>();
mText.setValue("logout");
}
public LiveData<String> getText() {
return mText;
}
}
Feels like there should be a built in solution but so far I have solved it like this.
I simply add a click listener on that menu option, in my case my logout button:
In Java -->
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.getMenu().findItem(R.id.logout).setOnMenuItemClickListener(menuItem -> {
logout();
return true;
});
In Kotlin -->
navView.getMenu().findItem(R.id.nav_logout).setOnMenuItemClickListener({ menuItem ->
logoutDialog()
true
})
I found two solution to handle it.
1. If you have register your fragment in navigation graph than
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
if (destination.getId() == R.id.logout){
logout();
}
}
});
2. If you don't have register fragment in navigation graph and you just want to handle click event on drawer menu.
mNavigationView.getMenu().findItem(R.id.nav_logout).setOnMenuItemClickListener(menuItem -> {
AppUtils.showLongToast("this works", getApplicationContext());
return true;
});
my navigation menu code
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
android:title="#string/menu_share" />
<item
android:id="#+id/logout"
android:icon="#drawable/logout"
android:title="Logout" />
<item
android:id="#+id/login"
android:icon="#drawable/logout"
android:title="Login" />
</menu>
code inside onResume method , this will hide either sign out or sign in button depending upon auth state of user
#Override
protected void onResume() {
super.onResume();
if (auth.getCurrentUser() == null) {
navigationView.getMenu().findItem(R.id.logout).setVisible(false);
navigationView.getMenu().findItem(R.id.login).setVisible(true);
// perform action when user is not logged in
} else {
navigationView.getMenu().findItem(R.id.logout).setVisible(true);
navigationView.getMenu().findItem(R.id.login).setVisible(false);
// perform action when user is already logged in
}
}
Handle navigation view item clicks here.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logout) {
auth.signOut();
onResume();
} else if (id == R.id.login) {
//handle event login button pressed
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Hope this will help you
I solve it with the help of constraint layout
I am developing an Android Studio app using Java. My app allows a user to sign in and view custom markers on a map with custom markers. When a user click on a custom marker they get taken to another activity.
My problem is, When accessing this activity via the custom marker, the app does not load the images stored in firebase.
Any Suggestions on what the problem might be? Thanks.
map activity that deals with the markers:
mMap.setOnMarkerClickListener
(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
if (marker.getTitle().equals("Mario's Italian"))
startActivity(new Intent(MapView.this,
ItalianMenu.class));
if (marker.getTitle().equals("Bamboo Tandoori"))
startActivity(new Intent(MapView.this,
IndianMenu.class));
if (marker.getTitle().equals("King Chinese
Takeaway"))
startActivity(new Intent(MapView.this,
ChineseMenu.class));
return false;
}
});
activity that opens up when a user clicks the marker:
package myapp.zerbu.partyloader;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import myapp.zerbu.partyloader.Common.Common;
import myapp.zerbu.partyloader.Interface.ItemClickListener;
import myapp.zerbu.partyloader.Model.Category;
import myapp.zerbu.partyloader.ViewHolder.MenuViewHolder;
public class ItalianMenu extends AppCompatActivity
implements
NavigationView.OnNavigationItemSelectedListener {
FirebaseDatabase database;
DatabaseReference category;
TextView txtName;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Mario's Italian");
setSupportActionBar(toolbar);
//Init Firebase
database = FirebaseDatabase.getInstance();
category = database.getReference("Category");
//Basket
FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
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 = (DrawerLayout)
findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new
ActionBarDrawerToggle(
this, drawer, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView)
findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Set Name for user
View headerView = navigationView.getHeaderView(0);
txtName =
(TextView)headerView.findViewById(R.id.txtName);
txtName.setText(Common.currentUser.getName());
//Load menu
recycler_menu = (RecyclerView)
findViewById(R.id.recycler_menu);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadMenu();
}
private void loadMenu() {
FirebaseRecyclerAdapter<Category, MenuViewHolder>
adapter = new FirebaseRecyclerAdapter<Category,
MenuViewHolder>(Category.class,
R.layout.activity_italian_menu, MenuViewHolder.class,
category) {
#Override
protected void populateViewHolder(MenuViewHolder
viewHolder, Category model, int position) {
viewHolder.txtMenuName.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage())
.into(viewHolder.imageView);
final Category clickItem = model;
viewHolder.setImageClickListener(new
ItemClickListener() {
#Override
public void onClick(View view, int position,
boolean isLongClick) {
Toast.makeText(ItalianMenu.this,
""+clickItem.getName(), Toast.LENGTH_SHORT).show();
}
});
}
};
recycler_menu.setAdapter(adapter);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout)
findViewById(R.id.drawer_layout);
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.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_restaurants) {
// Handle the camera action
} else if (id == R.id.nav_basket) {
} else if (id == R.id.nav_orders) {
} else if (id == R.id.nav_logout) {
}
DrawerLayout drawer = (DrawerLayout)
findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I am trying to include the generation of a random number in an android project with Navigation Drawer Menu. For the latter I’ve been following a youtube tutorial (Android Development Tutorials #12 - Generating a Random Number) which worked perfectly, but only in a basic android studio project. Being a java-newbie, I get stuck when trying to include the same Java Code into MainActivity.java that already contains the code for the Navigation Drawer Menu. I assume that the spot where I insert the respective sample code for number generation (Lines 114 to 126 in snippet) must be wrong somehow, and I’ve been trying different approaches within the file. But I always get the error: unreachable statement (in Line 114). Thx for any help in advance!
package...
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
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 = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
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.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();
//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();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layer) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
} else if (id == R.id.nav_second_layer) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layer) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
final TextView textOne = (TextView) findViewById(R.id.rndsampletext);
Button pushMe = (Button) findViewById(R.id.rndsamplebutton);
final String [] txtOptions = {"One", "Two", "Three"};
pushMe.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
int rando = (int) (Math.random() * 3);
textOne.setText(txtOptions[rando]);
};
});
}
}
you are returning true at begining:
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true; // here
it should be after u generate the random number:
I suggest u add the code to your onCreate() method of the activity
Like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
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();
}
});
//move this here
final TextView textOne = (TextView) findViewById(R.id.rndsampletext);
Button pushMe = (Button) findViewById(R.id.rndsamplebutton);
final String [] txtOptions = {"One", "Two", "Three"};
pushMe.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
int rando = (int) (Math.random() * 3);
textOne.setText(txtOptions[rando]);
};
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public class Navigationmenu extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigationmenu);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.Open,R.string.Close );
mToolbar = (Toolbar)findViewById(R.id.nav_action);
setSupportActionBar(mToolbar);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
Error.
How can I fix it?? My app is being forced to close when I click the button. Any one can help me please?
Error showing at "super.onCreate(savedInstanceState);" I don't know how to fix it.
I am unsure by your pictures but it seems that you are trying to add a navigation drawer to your project. You cannot add a navigation drawer on top of pre-existing code, rather it would be more cumbersome to do it that way.
In order to get the navigation drawer working you have to add some other code rather than what Android Studio provides. If you are adding a navigation drawer than the code needs to be added to MainActivity.java rather than its own file, and then you can implement that in each other fragment class to make the navigation drawer work.
What you might try adding is something like
public class Navigationmenu extends AppCompatActivity {
//Try this piece here
NavigationView navigationView = null;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigationmenu);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.Open,R.string.Close );
mToolbar = (Toolbar)findViewById(R.id.nav_action);
setSupportActionBar(mToolbar);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
//Try adding this to the code
navigationView = (NavigationView) findViewById(R.id.nav_view); //Declared in activity_main.xml
navigationView.setNavigationItemSelectedListener(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
If you are trying to make a Navigation Drawer with fragments, look to this complete MainActivity.java I have made, and note that everything in Navigation drawers runs on Fragments.
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, MainFragment.OnFragmentInteractionListener, LoginFragment.OnFragmentInteractionListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
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.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();
//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();
if (id == R.id.main) {
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.login) {
LoginFragment fragment = new LoginFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
//Leave blank
}
}
I have a class named MainActivity.java, this java contains Navigation Bar code.
If I want to build another activity named Contact.java and there also contains Navigation Bar code. How do I reuse Navigation Bar code from MainActivity.java to Contact.java? Can I create a class to solve it?
Here is my code:
package com.thisistap.isuper.www.contactbook;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TabHost;
import com.thisistap.isuper.www.contactbook.nav.*;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Button contact_button;
private TabHost mTabHost = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// defined elements from layout (it can be modified)
contact_button = (Button) findViewById(R.id.contact_button);
// --- [Start] defined elements from Navigation Bar (it cannot be modified from here) ---
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// --- [End] defined elements from Navigation Bar (it cannot be modified from here) ---
// --- [Start] Button Group ---
contact_button.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this,Contact.class);
MainActivity.this.startActivity(myIntent);
}
});
// --- [End] Button Group ---
}
// --- [Start] Navigation Bar Action (it cannot be modified from here) ---
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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();
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
Intent myIntent = new Intent(MainActivity.this,Contact.class);
MainActivity.this.startActivity(myIntent);
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
// --- [End] Navigation Bar Action (it cannot be modified from here) ---
}
I suggest you extendig your activities from a base activity and implement your common logic into this parent.
Just do this - Take all your drawer code in a BaseActivity and in XML of BaseActivity put DrawerLayout as parent along with a container(like you do it for fragments) and NavigationView. You can also look at this answer. It addresses the same issue.
Then extend BaseActivity to your MainActivity and instead of using setContentView(), inflate it in the container of your BaseActivity.
public class BaseActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// --- [Start] defined elements from Navigation Bar (it cannot be modified from here) ---
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// --- [End] defined elements from Navigation Bar (it cannot be modified from here) ---
}
// --- [Start] Navigation Bar Action (it cannot be modified from here) ---
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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();
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
Intent myIntent = new Intent(MainActivity.this,Contact.class);
MainActivity.this.startActivity(myIntent);
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
// --- [End] Navigation Bar Action (it cannot be modified from here) ---
}
Then extend in your MainActivity -
public class MainActivity extends BaseActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout containerParent = (FrameLayout) findViewById(R.id.container);
getLayoutInflater().inflate(R.layout.activity_main, containerParent);
contact_button = (Button) findViewById(R.id.contact_button);
}
}
Your BaseActivity XML should be like this -
<DrawerLayout --->
<FrameLayout ---/>
<NavigationView-------/>
</DrawerLayout/>