How to change xml parameters programmatically in Android - java

I have been working on an app that requires changing the nav menu options based on the User Type. To display the nav menu, i am using NavigationView. The only part i am stuck on is changing the app:menu parameter to another menu design (activity_nav_drawer2.xml).
activity_nav.xml
<?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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_nav"
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_nav"
app:menu="#menu/activity_nav_drawer" />
</android.support.v4.widget.DrawerLayout>
activity_nav_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_Home"
android:title="Home" />
<item
android:id="#+id/nav_Festivities"
android:title="Festivities" />
<!--<item-->
<!--android:id="#+id/nav_Announcements"-->
<!--android:title="Announcements" />-->
<!--<item-->
<!--android:id="#+id/nav_Payment"-->
<!--android:title="Payment" />-->
<!--<item-->
<!--android:id="#+id/nav_Settings"-->
<!--android:title="Settings" />-->
<item
android:id="#+id/nav_myCode"
android:title="My Code" />
<item
android:id="#+id/nav_readCode"
android:title="Read Code" />
</group>
<!--<group android:checkableBehavior="single">-->
<!--<item-->
<!--android:id="#+id/nav_organizer"-->
<!--android:title="Become an organizer" />-->
<!--<item-->
<!--android:id="#+id/nav_Legal"-->
<!--android:title="Legal" />-->
<!--</group>-->
</menu>
activity_nav2.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_Home"
android:title="Home" />
<item
android:id="#+id/nav_Festivities"
android:title="Create an Event" />
<item
android:id="#+id/nav_readCode"
android:title="Read Code" />
</group>
</menu>
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
public String eventKey;
private final int REQUEST_CAMERA_CODE = 1;
Intent intent = getIntent();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
MapFragment mapFragment = new MapFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(
R.id.content_nav,
mapFragment,
mapFragment.getTag()
).commit();
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView)
findViewById(R.id.nav_view);
navigationView.set
navigationView.setNavigationItemSelectedListener(this);
askPermissions(Manifest.permission.CAMERA, REQUEST_CAMERA_CODE);
}
#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.nav, 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_signOut){
FirebaseAuth.getInstance().signOut();
LoginManager.getInstance().logOut();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
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_Festivities) {
FestivitiesFragment festivitiesFragment = new FestivitiesFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(
R.id.content_nav,
festivitiesFragment,
festivitiesFragment.getTag()
).commit();
} else if (id == R.id.nav_myCode) {
getSupportFragmentManager().beginTransaction().replace(R.id.content_nav,new
CodeFragment()).commit();
} else if (id == R.id.nav_Home) {
MapFragment mapFragment = new MapFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(
R.id.content_nav,
mapFragment,
mapFragment.getTag()
).commit();
} else if (id == R.id.nav_readCode) {
ReadCodeFragment readCodeFragment = new ReadCodeFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(
R.id.content_nav,
readCodeFragment,
readCodeFragment.getTag()
).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void askPermissions(String permissions, int requestCode) {
if (ContextCompat.checkSelfPermission(this, permissions) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{permissions},
requestCode);
} else {
Toast.makeText(this, "Camera already Granted",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[]
permissions, #NonNull int[] grantResults) {
}
}

You can set visibility of different menu items according to the user type.
Instead of clearing the navigation_menu items, set visibilities for different items accordingly.

Related

How do you use a toolbar across all activies

I have made a toolbar and Navigation Drawer java class along with its XML, it works perfectly.
Here is the code:
Java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
//This part is new for NavigationDrawer:
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);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.items, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.ticket:
startActivity(new Intent(NavigationActivity.this, TicketMasterActivity.class));
break;
case R.id.recipe:
Intent goToRecipe = new Intent(NavigationActivity.this, RecipeSearchActivity.class);
startActivity(goToRecipe);
break;
case R.id.covid:
Intent goToCovid = new Intent(NavigationActivity.this, MainActivity_covid.class);
startActivity(goToCovid);
break;
case R.id.album:
Intent goToAlbum = new Intent(NavigationActivity.this, MainActivity.class);
startActivity(goToAlbum);
break;
case R.id.help:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(R.string.WelcomeTotal);
alertDialogBuilder.setMessage(R.string.WelcomeTotalMessage);
alertDialogBuilder.setPositiveButton("OK", (click2, arg) -> {
});
alertDialogBuilder.create().show();
}
return true;
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.ticket1) {
startActivity(new Intent(NavigationActivity.this, TicketMasterActivity.class));
} else if (id == R.id.recipe1) {
Intent goToRecipe = new Intent(NavigationActivity.this, RecipeSearchActivity.class);
startActivity(goToRecipe);
} else if (id == R.id.covid1) {
Intent goToCovid = new Intent(NavigationActivity.this, MainActivity_covid.class);
startActivity(goToCovid);
} else if (id == R.id.album1) {
Intent goToAlbum = new Intent(NavigationActivity.this, MainActivity.class);
startActivity(goToAlbum);
} else if (id == R.id.share) {
Toast.makeText(this, "this feature is not yet implemented", Toast.LENGTH_LONG).show();
} else if (id == R.id.send) {
Toast.makeText(this, "this feature is not yet implemented", Toast.LENGTH_LONG).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
XML:
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
android:id="#+id/toolbar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"/>
<androidx.drawerlayout.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:itemTextColor="#000000"
app:headerLayout="#layout/naviheader"
app:menu="#menu/navimenu"
tools:ignore="MissingClass" />
</androidx.drawerlayout.widget.DrawerLayout>
</LinearLayout>
I want to make it so that every activity uses this specific toolbar. And that every toolbar is preloaded with the items that I put inside in the java class. Is this possible and if so, how?
Thank you.
Create and Activity which will behave as a Parent Activity with your own custom toolbar.
Extend that activity where ever you want.

How to open New Activity by clicking Navigation Drawer Item in Android

How can I open New Activity by clicking a Navigation Drawer Menu Item?
Share_Home.java
public class Share_Home extends AppCompatActivity {
private long backPressedTime;
private ActionBarDrawerToggle toggle;
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_home);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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.
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
tabs.getTabAt(1).select();
toggle = new ActionBarDrawerToggle(this, drawer, R.string.open, R.string.close);
drawer.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_share_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.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_main"
app:menu="#menu/nav_menu_item" />
<include
layout="#layout/activity_tabs_menu"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.drawerlayout.widget.DrawerLayout>
nav_menu_item.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/nav_Setting"
android:icon="#drawable/setting_icon"
android:title="#string/nav_Setting" />
<item
android:id="#+id/nav_Help"
android:icon="#drawable/help_icon"
android:title="#string/nav_Help" />
<item
android:id="#+id/nav_Ratings"
android:icon="#drawable/rating_icon"
android:title="#string/nav_Ratings" />
<item
android:id="#+id/nav_About"
android:icon="#drawable/about_icon"
android:title="#string/nav_About" />
</menu>
Set a NavigationItemSelectedListener to you NavigationView:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id=menuItem.getItemId();
if (id == R.id.xxx){
Intent newIntent = new Intent(this, NewActivity.class);
startActivity(newIntent);
}
return true;
}
});
Also change your layout.
Instead of:
<androidx.drawerlayout.widget.DrawerLayout >
<include layout="#layout/app_bar_main" />
<com.google.android.material.navigation.NavigationView/>
<include layout="#layout/activity_tabs_menu"/>
</androidx.drawerlayout.widget.DrawerLayout>
Use:
<androidx.drawerlayout.widget.DrawerLayout >
<include layout="#layout/app_bar_main" />
<com.google.android.material.navigation.NavigationView/>
</androidx.drawerlayout.widget.DrawerLayout>
moving the <include layout="#layout/activity_tabs_menu"/> inside the app_bar_main layout.
You have to override onNavigationItemSelected and check the id of the selected menu item and then open Activity:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.activity1:
startActivity(new Intent(this, Activity1.class));
break;
case R.id.activity2:
startActivity(new Intent(this, Activity2.class));
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
And remember to add id to every item in menu layout:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/activity1"
android:title="#string/activity1" />
<item
android:id="#+id/activity2"
android:title="#string/activity2" />
</menu>
Here is how you can do it:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
final int itemId = item.getItemId();
if (itemId == R.id.nav_Setting) {
Intent newIntent = new Intent(getApplicationContext(), YourSettingActivity.class);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.nav_menu_item, menu);
return super.onCreateOptionsMenu(menu);
}
You get a listener in your NavigationView that listens to the item pressed. So you can set the listener and then start an activity when a particular item is pressed in the NavigationDrawer, like so:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.menu_item_1:
Intent intent = new Intent(this, ItemActivity.class);
startActivity(intent);
break;
}
}
});

What code i need to input, and where, to switch to a different fragment once item is clicked?

on my activity_main_drawer i got many items but i don't know what code and where it goes to add for switching fragment
<?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">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_contests"
android:icon="#drawable/ic_menu_camera"
android:title="#string/menu_home" />
<item
android:id="#+id/nav_rules"
android:icon="#drawable/irules"
android:title="#string/box_contest_rules" />
<item
android:id="#+id/nav_profile"
android:icon="#drawable/ic_baseline_face_24"
android:title="#string/profile_page" />
<item
android:id="#+id/nav_calendar"
android:icon="#drawable/icalendar"
android:title="#string/calendar_page" />
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/igallery"
android:title="#string/gallery_page" />
<item
android:id="#+id/nav_stats"
android:icon="#drawable/istats"
android:title="#string/stats_page" />
<item
android:id="#+id/nav_rank"
android:icon="#drawable/irank"
android:title="#string/rank_page" />
<item
android:id="#+id/nav_shop"
android:icon="#drawable/ishop"
android:title="#string/shop_page" />
<item
android:id="#+id/nav_setting"
android:icon="#drawable/ic_baseline_settings_24"
android:title="#string/setting_page" />
</group>
</menu>
this is the java HomePage where i am struggling to understand where and what code to add
public class HomePage extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
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)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#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_page, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
and this is one of the fragment java as example.
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel.class);
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
galleryViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
it would be great as example to switch from HomePage to GalleryFragment and back
try-->
put this in your mainactivity:-
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_contests) {
//intent to next activity
} else if (id == R.id.nav_rules) {
//just an example
String message = "Text I want to share.";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(share, "Title of the dialog the system will open"));
} else if (id == R.id.nav_profile) {
///your actions
}
} else if (id == R.id.nav_calendar) {
}
} else if (id == R.id.nav_gallery) {
}
} else if (id == R.id.nav_stats) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Demo
main_activity:
package ijsolutions.appnav;
import android.os.Bundle;
import androidx.core.view.GravityCompat;
import androidx.appcompat.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.view.Menu;
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);
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);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(R.id.nav_home);
}
#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);
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_home:
fragment = new Menu1();
//ft.addToBackStack(null);
break;
case R.id.nav_gallery:
fragment = new Menu2();
ft.addToBackStack(null);
break;
case R.id.nav_slideshow:
fragment = new Menu3();
ft.addToBackStack(null);
break;
}
//replacing the fragment
if (fragment != null) {
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//calling the method displayselectedscreen and passing the id of selected menu
displaySelectedScreen(item.getItemId());
//make this method blank
return true;
}}
Menu1
public class Menu1 extends Fragment {
public Menu1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_menu1, container, false);
}
}
xml of menu1
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Menu1"
android:background="#68a">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/Home"
android:layout_marginLeft="60dp"
android:textSize="50dp"
/>
so am not puting the rest menus as it is same
activitymain xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.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_main"
app:menu="#menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
activity_main_drawer
<?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">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_menu_camera"
android:title="#string/menu_home" />
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/ic_menu_gallery"
android:title="#string/menu_gallery" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/menu_slideshow" />
<item
android:id="#+id/nav_tools"
android:icon="#drawable/ic_menu_manage"
android:title="#string/menu_tools" />
</group>
<item android:title="Communicate">
<menu>
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
android:title="#string/menu_share" />
<item
android:id="#+id/nav_send"
android:icon="#drawable/ic_menu_send"
android:title="#string/menu_send" />
</menu>
</item>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
content_main:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
app_bar_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="#layout/content_main" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Add in you activity. It works
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_home) {
}else if (id == R.id.nav_logout) {
logOut(HomePage.this, "Logout due to nav. logout");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}

How to solve navigation bar with navigation bottom problem

My question is that I was trying to make a simple app, and I used both navigation bar and bottom navigation in the same activity, but I am having a simple problem, such as When I run the app, I'm in home fragment, but when I drag the navigation bar and click on movies, it goes into movies fragment, and my movies item got checked, but the problem is when I again click on home in bottom navigation menu than in my navigation menu the movies item still become checked. Please tell how should I do that if I click on home in bottom navigation then in my navigation bar my movies item become unchecked.
Hope you will understand my problem
Here is my code:-
MainActivity : -
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth mAuth;
private DrawerLayout drawerLayout;
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_search:
selectedFragment = new SearchFragment();
break;
case R.id.nav_features:
selectedFragment = new FeaturesFragment();
break;
case R.id.nav_myMusic:
selectedFragment = new MyMusicFragment();
break;
}
assert selectedFragment != null;
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
drawerLayout = findViewById(R.id.Drawyer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
mAuth = FirebaseAuth.getInstance();
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
Fragment selections = null;
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit();
}
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentuser;
currentuser = mAuth.getCurrentUser();
if (currentuser == null) {
SendUserToSelectTypeActivity();
}
}
private void SendUserToSelectTypeActivity() {
Intent testintent = new Intent(MainActivity.this, Selecttype.class);
testintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(testintent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
finish();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_Movies:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new MoviesFragment()).commit();
break;
case R.id.nav_log_out:
SendUserToSelectTypeActivity();
mAuth.signOut();
break;
case R.id.nav_live:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container
, new LiveVideosFragment()).commit();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
HomeFragment : -
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home , container , false);
}
}
navigation menu:-
<?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">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_Movies"
android:icon="#drawable/ic_movie"
android:title="Movies" />
<item
android:id="#+id/nav_live"
android:icon="#drawable/ic_movie"
android:title="Live Videos" />
</group>
<item android:title="Communicate">
<menu>
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_share_black_24dp"
android:title="Share" />
<item
android:id="#+id/nav_contact"
android:icon="#drawable/ic_report_black_24dp"
android:title="Report us" />
<item
android:id="#+id/nav_log_out"
android:icon="#drawable/ic_arrow_back_black_24dp"
android:title="Log Out" />
</menu>
</item>
</menu>
activity main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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/Drawyer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:fitsSystemWindows="true"
tools:context=".MainClasses.MainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottom_navigation">
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/design_default_color_primary_dark"
app:itemIconTint="#color/White"
app:itemTextColor="#color/White"
app:menu="#menu/bottom_navigation_menu" />
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/naviation_menu_main"
>
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
Please answer me if you found the solution
Make one file in drawable like "bottom_icon_color.xml"
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="#color/red" />
<item android:state_checked="false" android:color="#color/lightgray" />
</selector>
Then apply it to your bottom navigation
app:itemIconTint="#drawable/bottom_icon_color"
app:itemTextColor="#drawable/bottom_icon_color"
According to the problem you had mentioned in the question
you have to first store the previously clicked MenuItem and then make it as unchecked by using setCheckable(false) of MenuItem.
I'm assuming that the rest of all the functions are working, for example, check the item of NavigationView when the bottom navigation item is selected.
In your onNavigationItemSelected store, the clicked MenuItem in one variable say prevMenuItem of type MenuItem.
Now in your BottomNavigationView.OnNavigationItemSelectedListener() make this prevMenuItem as unchecked using this.
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.getMenu().findItem(previousMenuItem.getId()).setCheckable(false);

In my Fragment is the Layout of Mainactivity also shown

I'm working the first time with Fragments, so sorry if I did smt very stupid :D
I have a Navigation Drawer Activity. When I click in it on the first item i want to open a Fragment. When I open it, there is not only the Layout of the Fragment shown, but also the layout of my MainActivity, it looks very strange.
[1]: https://i.stack.imgur.com/iqTAq.png MainActivity
[2]: https://i.stack.imgur.com/kULQY.png Navigation Drawer
[3]: https://i.stack.imgur.com/T2vDJ.png First Fragment
How can I solve the problem?
Here is my code if you need it:
MainActivity(Navigation Drawer Templated, I wrote only in the onNavigationItemSelected, so that it goes to the fragment when I click on the first item:
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();
if (id == R.id.nav_camera) {
setTitle("First Fragment");
first first = new first();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment, first).commit();
} 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;
}
}
content_main (It should belong to MainActivity)
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.gsr.fragmenttest.MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="This is the Mainactivity, no fragemnt"/>
</FrameLayout>
</RelativeLayout>
First Fragment Activity
public class first extends Fragment {
Button btn;
TextView textView;
public first() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_first, container, false);
btn=(Button)v.findViewById(R.id.button);
textView=(TextView)v.findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textView.setText("Nice, it works !!");
}
});
// Inflate the layout for this fragment
return v;
}
}
And at least the fragment layout file
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.gsr.fragmenttest.first">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Hello Fragment"
android:textSize="50dp"/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
</FrameLayout>
I hope someone can help me :)
Add a background to your fragment layout, it should solve your problem.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white" //Your background color
tools:context="com.gsr.fragmenttest.first">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
...
I think the problem is in your activity layout
<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" >
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
try to change your main activity layout like above. Hope it will solve your problem.
1) implements first.OnOnFragmentInteractionListener
2) in onNavigationItemSelected method put this code
if (id == R.id.nav_camera) {
setTitle("First Fragment");
first first = new first();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment, new first()).commit();
3)In first fragment use this line
import android.app.Fragment;

Categories