Hi i'm trying to put an event Item click in my Navigation View from drawer it works fine, but the problem is the other items in my drawer stop working, it seems that putting an item click event on my navigation view affect my NavigationController
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bundy_clock);
dBhelper = new DBhelper(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, 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 item) {
int id = item.getItemId();
if(id == R.id.nav_logout){
AlertDialog.Builder conDialog = new AlertDialog.Builder(BundyClock.this);
conDialog.setTitle("Confirm");
conDialog.setMessage("Are you sure you want to log out?");
conDialog.setCancelable(false);
conDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(BundyClock.this, MainActivity.class));
Toast.makeText(getApplicationContext(),"Successfully Logout",Toast.LENGTH_SHORT).show();
finish();
}
});
conDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog sdialog = conDialog.create();
sdialog.show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
}
You have to use NavigationUI.onNavDestinationSelected to handle this. Check below:
boolean handled = NavigationUI.onNavDestinationSelected(menuItem, navController);
if (!handled) {
if(id == R.id.nav_logout){
AlertDialog.Builder conDialog = new AlertDialog.Builder(BundyClock.this);
conDialog.setTitle("Confirm");
conDialog.setMessage("Are you sure you want to log out?");
conDialog.setCancelable(false);
conDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(BundyClock.this, MainActivity.class));
Toast.makeText(getApplicationContext(),"Successfully Logout",Toast.LENGTH_SHORT).show();
finish();
}
});
conDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog sdialog = conDialog.create();
sdialog.show();
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return handled;
Related
My MainActivity uses onNavigationItemSelected(MenuItem item) that includes an activity. But somehow it won't open the other fragments that I have on the drawer. I can open the fragments if i delete navigationView.setNavigationItemSelectedListener(this). But then I can't open BookingActivity.
My MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
//region Properties
private AppBarConfiguration mAppBarConfiguration;
ImageButton settings_btn;
//endregion
#Override
protected void onStart() {
super.onStart();
ProductDatabase productDb = new ProductDatabase();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
settings_btn = findViewById(R.id.btn_settings);
settings_btn.setOnClickListener(v ->
startActivity(new Intent(MainActivity.this, SettingsActivity.class)));
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(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_login, R.id.nav_treatments, R.id.nav_product, R.id.nav_about, R.id.nav_contactUs)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
navigationView.setNavigationItemSelectedListener(this); // Fragments work if I remove this line, but not BookingActivity
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_booking) {
startActivity(new Intent(this, BookingActivity.class));
} else if (id == R.id.nav_home) {
} else if (id == R.id.nav_product) {
// What to write here to open ProductFragment?
} else if (id == R.id.nav_treatments) {
} else if (id == R.id.nav_about) {
} else if (id == R.id.nav_contactUs) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
please try this link How to go to fragment from activity
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_booking) {
startActivity(new Intent(this, BookingActivity.class));
} else if (id == R.id.nav_home) {
} else if (id == R.id.nav_product) {
// here you will set intent
} else if (id == R.id.nav_treatments) {
} else if (id == R.id.nav_about) {
} else if (id == R.id.nav_contactUs) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
I keep getting an IllegalArgumentException in my MainActivity code, please help me! The error is being shown on the line
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
I am trying to add in the QR code reader into the Main Activity, but when I did so, this error popped up
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private SharedPreferences appData;
private Button scan_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_scan);
scan_button = (Button) findViewById(R.id.btnScan);
final Activity activity = this;
scan_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*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_transaction, R.id.nav_qrcode,
R.id.nav_login, R.id.nav_logout, R.id.nav_signup, R.id.nav_rewards, R.id.nav_scan)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
appData = getSharedPreferences("appData", this.MODE_PRIVATE);
SharedPreferences.Editor editor = appData.edit();
editor.putFloat("Point", 0);
//editor.putBoolean("SAVE_LOGIN_DATA", checkBox.isChecked());
editor.putString("ID", "");
editor.putString("PWD", "");
editor.apply();
//Navigation.findNavController(navigationView).navigate(R.id.nav_login);
}
#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 onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public boolean onChangeMenuItem() {
NavigationView navigationView = findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
MenuItem nav_dashboard = menu.findItem(R.id.nav_login);
nav_dashboard.setVisible(false);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "You Cancelled the Scan", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
String scanResult = data.getStringExtra("SCAN_RESULT");
int pointsAdded = Integer.parseInt(scanResult);
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
I am making an online food ordering app.My app was running good but when i add cart code it is showing abnormal behaviour like the cart button takes me to first screen i started.following is the cart.java code
public class Cart extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference requests;
TextView txtTotalPrice;
FButton btnPlace;
List<Order> cart=new ArrayList<>();
CartAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
//Firebase
database = FirebaseDatabase.getInstance();
requests = database.getReference("Requests");
//Init
recyclerView = (RecyclerView) findViewById(R.id.listCart);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
txtTotalPrice = (TextView) findViewById(R.id.total);
btnPlace =(FButton)findViewById(R.id.btnPlaceOrder);
btnPlace.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
showAlertDialog();
}
});
loadlistfood();
}
private void showAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Cart.this);
alertDialog.setTitle("One more step!");
alertDialog.setMessage("Enter your Address: ");
final EditText edtAddress = new EditText(Cart.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
edtAddress.setLayoutParams(lp);
alertDialog.setView(edtAddress);//add edt text to alert box
alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Request request = new Request(
Common.currentUser.getPhone(),
Common.currentUser.getName(),
edtAddress.getText().toString(),
txtTotalPrice.getText().toString(),
cart
);
//submit to firebase
//we will use system.currntMill to key
requests.child(String.valueOf(System.currentTimeMillis()))
.setValue(request);
//Delete cart
new Database(getBaseContext()).cleanCart();
Toast.makeText(Cart.this, "Thank you,Order placed", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void loadlistfood() {
cart=new Database(this).getCarts();
adapter=new CartAdapter(cart,this);
recyclerView.setAdapter(adapter);
//calculate price
int total=0;
for(Order order:cart)
total+=(Integer.parseInt(order.getPrice()))*(Integer.parseInt(order.getQuantity()));
Locale locale=new Locale("en","US");
NumberFormat fmt=NumberFormat.getCurrencyInstance(locale);
txtTotalPrice.setText(fmt.format(total));
}
Rest i had put a intent in where cart button is put and else i have cartAdapter class and request.java.If you need them i will edit the question.Please help me.
Here is code that take me to cart.java.
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FirebaseDatabase database;
DatabaseReference category;
TextView txtFullName;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Category,MenuViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Menu");
setSupportActionBar(toolbar);
//init firebase
database = FirebaseDatabase.getInstance();
category = database.getReference("Category");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cartIntent = new Intent(getApplicationContext(),Cart.class);
startActivity(cartIntent);
}
});
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);
//set name for user
View headerView = navigationView.getHeaderView(0);
txtFullName = (TextView)headerView.findViewById(R.id.txtFullName);
txtFullName.setText(Common.currentUser.getName());
//Load menu
recycler_menu=(RecyclerView)findViewById(R.id.recycler_meu);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadMenu();
}
private void loadMenu() {
adapter=new FirebaseRecyclerAdapter<Category, MenuViewHolder>(Category.class,R.layout.menu_item,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.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
//Get category id and send to new Activity
Intent foodList=new Intent(Home.this,FoodList.class);
foodList.putExtra("CategoryId",adapter.getRef(position).getKey());
startActivity(foodList);
}
});
}
};
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_menu) {
// Handle the camera action
} else if (id == R.id.nav_cart) {
// Intent cartIntent = new Intent(Home.this,Cart.class);startActivity(cartIntent);
} else if (id == R.id.nav_orders) {
} else if (id == R.id.log_out) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Thank you in advance
I have developed an android application using java and android studio. But when I click the items in the navigation drawer, I expect it to display a dialog, but nothing happens. Also when I try to setText in the drawer, the application crashes. I'm new to android development. Please, I would greatly appreciate help.
Below is my code:
private TextView name;
public TextView email;
public TextView contact;
private DrawerLayout drawerLayout;
AlertDialog.Builder builder;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout=(DrawerLayout) findViewById(R.id.drawer);
builder=new AlertDialog.Builder(MainActivity.this);
name=(TextView) findViewById(R.id.myname);
email=(TextView) findViewById(R.id.myemail);
contact=(TextView) findViewById(R.id.mycontact);
actionBarDrawerToggle=new ActionBarDrawerToggle(this, drawerLayout,R.string.open,R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//RECEIVING THE INTENT
/* Get values from Intent
Intent intent = getIntent();
String myname = intent.getStringExtra("dname");
String myemail = intent.getStringExtra("demail");
String mycontact = intent.getStringExtra("dcontact");
name.setText(myname);
email.setText(myemail);
contact.setText(mycontact);
builder.setTitle("Log In Successful");
builder.setMessage("Welcome, "+myname);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getApplicationContext(),"Clock Out Cancelled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();*/
//name.setText(response);
/*try {
JSONObject jsonObject = new JSONObject(fname);
String fstname=jsonObject.getString("clockTym");
String lstname=jsonObject.getString("timediff");
String demail=jsonObject.getString("penalty");
String dcontact=jsonObject.getString("tot_penalty");
name.setText(fstname+" "+lstname);
email.setText(demail);
contact.setText(dcontact);
} catch (JSONException e) {
e.printStackTrace();
}*/
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.cin){
// Handle the camera action
builder.setTitle("Log In Successful");
builder.setMessage("Welcome, ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getApplicationContext(),"Clock Out Cancelled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
} else if (id == R.id.db) {
builder.setTitle("Log In Successful");
builder.setMessage("Welcome, ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getApplicationContext(),"Clock Out Cancelled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
} else if (id == R.id.permit) {
builder.setTitle("Log In Successful");
builder.setMessage("Welcome, ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getApplicationContext(),"Clock Out Cancelled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
} else if (id == R.id.cout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
You not initializing the navigation drawer which actually contains the list item though you already have onNavigationItemSelected listener so inside oncreate initialize the navigation view and attach the listener like
NavigationView navView = (NavigationView) findViewById(R.id.your_nav_id);
navView.setNavigationItemSelectedListener(this);
I am trying to use two framelayouts to load the content. My problem is both pages are showing data at the same time. I want to use setVisibilty method in the main java file. When one frame is showing data the other frame hides automatically. Could anyone tell me the java codes. Here is the xml file:
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<FrameLayout
android:id="#+id/content_frametwo"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
I am giving you the java file here:-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
}
private void setFrameVisibility(boolean frameOneVisible){
if (frameOneVisible){
findViewById(R.id.content_frame).setVisibility(View.VISIBLE);
findViewById(R.id.content_frametwo).setVisibility(View.GONE);
} else {
findViewById(R.id.content_frame).setVisibility(View.GONE);
findViewById(R.id.content_frametwo).setVisibility(View.VISIBLE);
}
}
#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.homepage) {
Intent homepage = new Intent (MainActivity.this, MainActivity.class);
startActivity(homepage);
// Handle the camera action
} else if (id == R.id.foodpage) {
//handle the food page here
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
} else if (id == R.id.schedulepage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ScheduleFragment())
.commit();
} else if (id == R.id.emotionspage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new EmotionsFragment())
.commit();
} else if (id == R.id.basicneedspage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frametwo
, new BasicneedsFragment())
.commit();
} else if (id == R.id.exit) {
askBeforeExit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void onBackPressed() {
askBeforeExit();
}
private void askBeforeExit(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Confirm Exit");
builder.setMessage("Are you sure you want to quit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert=builder.create();
alert.show();
}
}
You could make a function to set them both, but then you will have to make sure you always use that function:
private void setFrameVisibility(boolean frameOneVisible) {
if (frameOneVisible) {
findViewById(R.id.content_frame).setVisibility(View.VISIBLE);
findViewById(R.id.content_frametwo).setVisibility(View.GONE);
} else {
findViewById(R.id.content_frame).setVisibility(View.GONE);
findViewById(R.id.content_frametwo).setVisibility(View.VISIBLE);
}
}
You can implement this by using this code:
inside onCreateView:
frameLayout1 = (FrameLayout) findViewById(R.id.frameLayout1);
frameLayout2 = (FrameLayout) findViewById(R.id.frameLayout2);
When ever you want to change visibility:
frameLayout1.setVisibility(View.VISIBLE);
frameLayout2.setVisibility(View.GONE);