Android Naviagtion Items not Displaying Fragments - android

I have created a navHost which i would like to replace with fragments from the my navGraph and using the onNavigationItemSelected event listener i want the navHost replaced by every navigation item i have selected. But i still dont know why the FragmentTransaction.replace method doesnt get the navHost replaced by the navGraph commited to
content_main.xml
<?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:showIn="#layout/app_bar_main">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation"></fragment>
</androidx.constraintlayout.widget.ConstraintLayout>
mobile_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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/mobile_navigation"
app:startDestination="#+id/nav_home">
<fragment
android:id="#+id/nav_home"
android:name="com.example.airtimeflip.ui.fragments.home.HomeFragment"
android:label="#string/menu_home"
tools:layout="#layout/fragment_home" />
<fragment
android:id="#+id/nav_profile"
android:name="com.example.airtimeflip.ui.fragments.profile.ProfileFragment"
android:label="#string/profile"
tools:layout="#layout/fragment_profile" />
<fragment
android:id="#+id/nav_manager"
android:name="com.example.airtimeflip.ui.fragments.manager.AccountManagerFragment"
android:label="#string/menu_slideshow"
tools:layout="#layout/fragment_account_manager" />
<fragment
android:id="#+id/nav_atc"
android:name="com.example.airtimeflip.ui.fragments.atc.AtcFragment"
android:label="#string/menu_gallery"
tools:layout="#layout/fragment_atc" />
<fragment
android:id="#+id/nav_buy_airtime"
android:name="com.example.airtimeflip.ui.fragments.buy_airtime.BuyAirtimeFragment"
android:label="#string/menu_tools"
tools:layout="#layout/fragment_buy_airtime" />
<fragment
android:id="#+id/nav_send_money"
android:name="com.example.airtimeflip.ui.fragments.send_money.SendMoneyFragment"
android:label="#string/menu_share"
tools:layout="#layout/fragment_send_money" />
</navigation>
MainActivity.java
package com.example.airtimeflip;
import android.os.Bundle;
import com.example.airtimeflip.config.GlobalUtilConfig;
import com.example.airtimeflip.ui.fragments.atc.AtcFragment;
import com.example.airtimeflip.ui.fragments.buy_airtime.BuyAirtimeFragment;
import com.example.airtimeflip.ui.fragments.home.HomeFragment;
import android.util.Log;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.GravityCompat;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavController;
import androidx.navigation.NavDestination;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.airtimeflip.ui.fragments.manager.AccountManagerFragment;
import com.example.airtimeflip.ui.fragments.profile.ProfileFragment;
import com.example.airtimeflip.ui.fragments.send_money.SendMoneyFragment;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "MainActivity";
private AppBarConfiguration mAppBarConfiguration;
private DrawerLayout drawer;
// private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
//adding event listener to the navigation view
navigationView.setNavigationItemSelectedListener(this);
// 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_manager,
R.id.nav_atc, R.id.nav_buy_airtime, R.id.nav_send_money)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
}
#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();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
menuItem.setChecked(true);
try {
if (id == R.id.nav_home){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.nav_host_fragment, new HomeFragment());
ft.commit();
} else if (id == R.id.nav_atc){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.nav_host_fragment, new AtcFragment());
ft.commit();
} else if (id == R.id.nav_buy_airtime){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.nav_host_fragment, new BuyAirtimeFragment());
ft.commit();
}else if (id == R.id.nav_profile){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.nav_host_fragment, new ProfileFragment());
ft.commit();
}else if (id == R.id.nav_manager){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.nav_host_fragment, new AccountManagerFragment());
ft.commit();
}else if (id == R.id.nav_send_money){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.nav_host_fragment, new SendMoneyFragment());
ft.commit();
}
} catch (Exception e) {
//e.printStackTrace();
Log.d(TAG, "onNavigationItemSelected: "+ e.toString());
}
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}

Something you are doing wrong here. You are using wrong id.
R.id.nav_home, R.id.nav_atc, R.id.nav_buy_airtime ,R.id.nav_profile, R.id.nav_manager, R.id.nav_send_money. These all are navigation fragment id. But instead you should use menu id.
Also When using Navigation, Navigate to destination using NavController.
Replace this code, this code will also work but the navigation architecture comes with more convenient way of doing the things.
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.nav_host_fragment, new HomeFragment());
ft.commit();
with this
navController.navigate(R.id.nav_atc);
Also this lines are redundant
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // No need use the same which you have initialize in onCreate
drawerLayout.closeDrawer(GravityCompat.START)
Just use
drawerLayout.closeDrawer(GravityCompat.START)

Related

i have used Bottom navigaion with navigation drawer both with fragments

I an Working On a project which uses navigation drawer with bottom navigation view
my navigation drawer is working fine but when i click any options from bottom navigation it gets selected but not shows anything in framelayout Here Is My XML File Please Help Me..
none of fragment of bottom navigation drawer are showing
<?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:orientation="vertical"
tools:context=".Home_Activity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="?attr/actionBarSize">
<FrameLayout
android:id="#+id/framelayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
android:soundEffectsEnabled="true"
app:itemIconTint="#color/yellow"
app:itemTextColor="#color/blue"
app:menu="#menu/bottom_nav" />
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/navigation_drawer_header"
app:itemHorizontalPadding="40dp"
app:menu="#menu/navigation_menu" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#fecd99"
app:navigationIcon="#drawable/baseline_sort_24px" />
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</androidx.drawerlayout.widget.DrawerLayout>
And Here Is My Java File
package com.anshdev.anshapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.appcompat.widget.Toolbar;
import com.anshdev.anshapp.Navigation_drawer.about_us_fragment;
import com.anshdev.anshapp.Navigation_drawer.categories_fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
public class Home_Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
Fragment fragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
/* <-------------------------Hooks--------------------->*/
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
toolbar = findViewById(R.id.toolbar);
/*<-------------------Tool Bar-------------->*/
setSupportActionBar(toolbar);
/*<-------------------NAVIGATION DRAWER MENU-------------->*/
navigationView.bringToFront();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.home_nav);
//--------------------BOTTOM NAVIGATION-----------------------
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav);
bottomNavigationView.setOnNavigationItemSelectedListener(selectedListener);
//default-selected-bottom-nav
Home home = new Home();
FragmentTransaction ft1 = getSupportFragmentManager().beginTransaction();
ft1.replace(R.id.framelayout, home, null);
ft1.commit();
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.home_nav:
Intent intent = new Intent(this, Home_Activity.class);
startActivity(intent);
break;
case R.id.categories_nav:
fragment = new categories_fragment();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.about_us_nav:
fragment = new about_us_fragment();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
private void loadFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, fragment).commit();
drawerLayout.closeDrawer(GravityCompat.START);
fragmentTransaction.addToBackStack(null);
}
private BottomNavigationView.OnNavigationItemSelectedListener selectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home_bottom_nav:
Home home = new Home();
FragmentTransaction ft1 = getSupportFragmentManager().beginTransaction();
ft1.replace(R.id.framelayout, home, null);
ft1.commit();
return true;
case R.id.menu_bottom_nav:
Menu menu = new Menu();
FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction();
ft2.replace(R.id.framelayout, menu, null);
ft2.commit();
return true;
case R.id.fav_nav_bottom:
Favourites Fav = new Favourites();
FragmentTransaction ft3 = getSupportFragmentManager().beginTransaction();
ft3.replace(R.id.framelayout, Fav, null);
ft3.commit();
return true;
case R.id.user_bottom_profile:
User_Profile Userprofile = new User_Profile();
FragmentTransaction ft4 = getSupportFragmentManager().beginTransaction();
ft4.replace(R.id.framelayout, Userprofile, null);
ft4.commit();
return true;
}
return false;
}
};
}
Please Help Me...

Problem while using navigation drawer and bottom navigation bar with different menu

The java class in which have used both..
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
public class NavigActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private BottomNavigationView bottomNavigationView;
private NavController navController;
private AppBarConfiguration appBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navig);
drawerLayout = findViewById(R.id.drawer);
navigationView = findViewById(R.id.navigationView);
navigationView.setNavigationItemSelectedListener(this);
bottomNavigationView = findViewById(R.id.bottomNavigationView);
navController = Navigation.findNavController(this, R.id.nav_host_fragment);
appBarConfiguration = new AppBarConfiguration.Builder(new int[]{R.id.home, R.id.addNewProduct, R.id.notifications,R.id.user_details,R.id.settings,R.id.help})
.setDrawerLayout(drawerLayout)
.build();
NavigationUI.setupActionBarWithNavController(this, navController,appBarConfiguration);
NavigationUI.setupWithNavController(bottomNavigationView, navController);
NavigationUI.setupWithNavController(navigationView, navController);
navigationView.setNavigationItemSelectedListener(this);
}
public boolean onOptionsItemSelected(MenuItem item) {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.onNavDestinationSelected(item, navController)
|| super.onOptionsItemSelected(item);
}
public boolean onSupportNavigateUp(){
return NavigationUI.navigateUp(navController, appBarConfiguration);
}
public void onBackPressed(){
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else
super.onBackPressed();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment = null;
int id= menuItem.getItemId();
if(id == R.id.user_details)
{
fragment = new UserFragment();
}
if(id == R.id.settings)
{
}
if(id == R.id.help)
{
}
if(id== R.id.logout)
{
MainActivity obj = new MainActivity();
obj.logout();
startActivity(new Intent(NavigActivity.this, MainActivity.class));
}
if(fragment != null)
{
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
It's Layout file..
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
android:id="#+id/drawer"
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=".NavigActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/main" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:background="#color/colorAccent"
app:itemIconTint="#color/nav"
app:itemTextColor="#color/nav"
app:menu="#menu/main"
android:id="#+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
</com.google.android.material.bottomnavigation.BottomNavigationView>
</androidx.constraintlayout.widget.ConstraintLayout>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView
app:menu="#menu/side_main"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/navigationView"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
></com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
when I am clicking on the user option the menu it does not directs to the fragment, it displays its feature in main page and then those are displayed in every page in the app..
The User Fragment is
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class UserFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_user, null);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
And its layout file is
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User"
android:textSize="28dp"
android:layout_centerInParent="true"
/>
</RelativeLayout>
Any help would be appreciated..And If anyone can suggest a better way of using navigation drawer and bottom navigation in same app then I would be very grateful to him..

Error: Cannot find symbol variable

I watched a tutorial from this guy:
https://www.youtube.com/watch?v=-SUvA1fXaKw
At the end (about 9:55) he wrote down:
if(fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_main, fragment);
ft.commit();
I renamed my content_main in activity_main_menu1_start_seite and I thought I could just replace the content_main with activity_main_menu1_start_seite, but then it says "cannot find Symbol variable activity_main_menu1_start_seite"
Maybe you Need my whole Code.
I marked you the error as the Blockquote.
Sorry for any issues (I am new to this site)
package com.d_and_d_studios.test3;
import android.Manifest;
import android.app.Fragment;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
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.view.View;
import android.widget.TextView;
import android.widget.Toast;
import at.markushi.ui.CircleButton;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
CircleButton btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_drawer);
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.setNavigationItemSelectedListener(this);
btn = (CircleButton) findViewById(R.id.circleButton);
}
#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;
}
//Brauche ich vielleicht doch noch irgendwann!
//#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 id) {
Fragment fragment = null;
switch (id) {
case R.id.nav_powersavingmode:
fragment = new Menu_2_Energiesparmodus();
break;
case R.id.nav_feedback:
fragment = new Menu_3_Bewerte_die_App();
break;
case R.id.nav_send:
fragment = new Menu_4_Teile_uns_Fehler_mit();
}
if(fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.activity_main_menu1_start_seite, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_powersavingmode) {
// Handle the camera action
} else if (id == R.id.nav_feedback) {
} else if (id == R.id.nav_send) {
}
displaySelectedScreen(id);
return true;
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
android:background="#color/backgroundcolor"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.d_and_d_studios.test3.MainActivity"
tools:showIn="#layout/toolbar_main">
<at.markushi.ui.CircleButton
android:id="#+id/circleButton"
android:layout_width="116dp"
android:layout_height="116dp"
android:layout_centerInParent="true"
android:src="#drawable/ic_power_settings_new_black_24dp"
app:cb_color="#000"
app:cb_pressedRingWidth="20dp"
tools:layout_editor_absoluteY="178dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/menu1_text1"
android:fontFamily="sans-serif"
android:textColor="#color/colorPrimary"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintVertical_bias="0.23" />
</android.support.constraint.ConstraintLayout>
The R class is generated based on the names and content of files in the res subfolder of your project. If Android Studio does not do this automatically, you can force a manual build by clicking the Build button on the toolbar.
Which xml contains an ID of activity_main_menu1_start_seite?
Renaming the XML file only affects the R.layout values, and include tags in the other xml files.
If it can't find R.id.activity_main_menu1_start_seite, then nothing contains android:id with that name. Specifically, you need a ViewGroup (such as a FrameLayout) within activity_main_drawer.xml with that value

Navigation Drawer doesn't show fragments

I've created a new Android Studio Project and my MainActivity is a Navigation Drawer Activity.
So, I can't show up fragments. I've read many post on internet and here too.
Explaining:
I open navigation drawer, select menu "Podcast".
PodcastsFragment should be shown, but it still showing activity.
MainActivity code:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
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 com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Tracker mTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// [START shared_tracker]
// Obtain the shared Tracker instance.
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
// [END shared_tracker]
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
protected void onResume() {
Log.i("TESTE", "Setting screen name: " + "teste");
mTracker.setScreenName("Main " + "teste");
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
super.onResume();
}
#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();
Fragment fragment = null;
FragmentTransaction ft = null;
if (id == R.id.nav_podcasts) {
Log.d("Clicked:", "nav_podcasts");
fragment = new PodcastsFragment();
} else if (id == R.id.nav_feed) {
//fragment = new FeedFragment();
Log.d("Clicked:", "nav_feed");
//fragment = new FeedFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FeedFragment ff = new FeedFragment();
fragmentTransaction.add(R.id.container_body, ff);
fragmentTransaction.commit();
} else if (id == R.id.nav_downloads) {
//fragment = new DownloadsFragment();
Log.d("Clicked:", "nav_downloads");
} else if (id == R.id.nav_add) {
//fragment = new OPMLFragment();
Log.d("Clicked:", "nav_add");
} else if (id == R.id.nav_settings) {
//fragment = new SettingsFragment();
Log.d("Clicked:", "nav_settings");
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container_body, fragment).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
PodcastsFragment code:
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class PodcastsFragment extends Fragment {
public PodcastsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_podcasts, container, false);
View rootView = inflater.inflate(R.layout.fragment_podcasts, container, false);
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
app_bar_main code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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"
android:fitsSystemWindows="true"
tools:context="com.test.test.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.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" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main"/>
<!--<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />-->
</android.support.design.widget.CoordinatorLayout>
activity_main code:
<?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_main"
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_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
content_main code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_main"
tools:context="com.test.test.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="teste"/>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</RelativeLayout>
Make the drawer's list in Your activity and add setOnItemClickListener().When the user selects an item in the drawer's list, the system calls onItemClick() on the OnItemClickListener given to setOnItemClickListener().
What you do in the onItemClick() method depends on how you've implemented your app structure. In the following example, selecting each item in the list inserts a different Fragment into the main content view (the FrameLayout element identified by the R.id.content_frame ID):
for more delail please read these articles youtube and github example
Latest - If you use Navigation Architecture Component, then you don't have to manually connect your fragments to your drawer MenuItem. The system will automatically tie you MenuItem to specific fragment If the id of the MenuItem in your menu/xyz_menu.xml matches the id of the destination in navigation/xyz_nav.xml, the NavController can then navigate to that destination.
Follow the correct steps mentioned in the official documentation : https://developer.android.com/guide/navigation/navigation-ui#Tie-navdrawer
Note :
They have a sample app linked to the same article which you can refer.
To get this is effect, do not implement onNavigationItemSelected otherwise it will override the system let you handle the navigation.

Opening a fragment(s) in home activity

I've been searching through Stack Overflow but couldn't seem to find something useful about this issue I am having ..
Below I have attached the code for the Home Activity that I have, and the XML file for it. I cant seem to get my head around what the problem is, I dunno what I am doing wrong. I want to show the content of a third class (e.g. the a different Fragment class for each of my fragments, basically I want to be able to show all the of the fragments in the same fragment holder in the home activity.. in this case I am trying to open the fragment Bookmarks (men.bookmarks)..
Any suggestions guys?
I didn't include the code for the fragment as it would be a lot of classes then, but If you need it, tell me :) ..
XML file for my HomeActivity:
<?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_home"
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_home"
app:menu="#menu/activity_home_drawer" />
<fragment
android:name="com.nooriandroid.n007.mybookmarks_v1.Fragment_Bookmarks"
android:id="#+id/fragBookmarks"
android:layout_weight="2"
android:layout_width="25dp"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
package com.nooriandroid.n007.mybookmarks_v1;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
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.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Activity_Home extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
//--------------Variables---------------------//
private String date_pattern = "hh:mm dd-MM-yyyy";
private Fragment fragment_bookmarks;
private Fragment_Favorite fragment_favorite;
private Fragment_Category fragment_category;
private Fragment_SharedWith_me fragment_sharedWith_me;
private Fragment_Myshared fragment_myshared;
private Activity_Home homeActivity;
private Fragment_Item_Container fragment_item_container;
private User user;
private boolean frag_favorite_visible = false, frag_bookmark_visible = false, frag_category_visible = false,
frag_myshared_visible = false, frag_sharedwithme__visible = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
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);
//---------------Customized------------------//
setTitle("Home");
ActionBar ab = getSupportActionBar();
ab.setLogo(R.mipmap.ic_logolight);
ab.setDisplayUseLogoEnabled(true);
ab.setDisplayShowHomeEnabled(true);
fragment_favorite = new Fragment_Favorite();
fragment_bookmarks = new Fragment_Bookmarks();
fragment_category = new Fragment_Category();
fragment_myshared = new Fragment_Myshared();
fragment_sharedWith_me = new Fragment_SharedWith_me();
fragment_item_container = new Fragment_Item_Container();
homeActivity = this;
FragmentManager fragmentManager = getFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, fragment_favorite);
fragmentTransaction.add(R.id.fragment_container, fragment_bookmarks);
fragmentTransaction.add(R.id.fragment_container, fragment_category);
fragmentTransaction.add(R.id.fragment_container, fragment_myshared);
fragmentTransaction.add(R.id.fragment_container, fragment_sharedWith_me);
frag_favorite_visible = true;
fragmentTransaction.hide(fragment_bookmarks);
fragmentTransaction.hide(fragment_category);
fragmentTransaction.hide(fragment_myshared);
fragmentTransaction.hide(fragment_sharedWith_me);
fragmentTransaction.commit();
goHomeOnclicked();
user = new User();
user = (User) getIntent().getSerializableExtra("currentuser");
}
#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);
rundUserSettings();
SimpleDateFormat format = new SimpleDateFormat(date_pattern);
String current_date = format.format(new Date());
TextView nav_textview_Date = (TextView) findViewById(R.id.textView_Date);
nav_textview_Date.setText(current_date);
TextView nameLast_textView = (TextView) findViewById(R.id.textView_UsernameLastname);
nameLast_textView.setText("" + user.getName() + " " + user.getLast_name());
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.men_newItem) {
Intent intent_NewItem = new Intent("com.nooriandroid.n007.mybookmarks_v1.Activity_NewItem");
startActivity(intent_NewItem);
} else if (id == R.id.men_bookmarks) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
fragmentTransaction.show(fragment_bookmarks);
frag_bookmark_visible = true;
this.setTitle("Bookmarks"); ///Ombytnings Zirt
fragmentTransaction.commit(); ///
} else if (id == R.id.men_category) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
frag_category_visible= true;
fragmentTransaction.show(fragment_category);
fragmentTransaction.commit();
this.setTitle("Categories ");
Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
}
else if (id == R.id.men_share) {
Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
} else if (id == R.id.men_sharedwithme) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
frag_sharedwithme__visible = true;
fragmentTransaction.show(fragment_sharedWith_me);
fragmentTransaction.commit();
this.setTitle("Shared with me");
Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
} else if (id == R.id.men_myshared) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
frag_myshared_visible = true;
fragmentTransaction.show(fragment_myshared);
fragmentTransaction.commit();
this.setTitle("My shared");
Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void checkFragmentsStatus(FragmentTransaction fragmentTransaction){
if (frag_favorite_visible){
frag_favorite_visible = false;
fragmentTransaction.hide(fragment_favorite);
}else if (frag_bookmark_visible){
frag_bookmark_visible = false;
fragmentTransaction.hide(fragment_bookmarks);
}else if (frag_category_visible){
frag_category_visible = false;
fragmentTransaction.hide(fragment_category);
}else if (frag_myshared_visible){
frag_myshared_visible = false;
fragmentTransaction.hide(fragment_myshared);
}else if (frag_sharedwithme__visible){
frag_sharedwithme__visible = false;
fragmentTransaction.hide(fragment_sharedWith_me);
}
}
private void goHomeOnclicked(){
findViewById(R.id.toolbar).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!frag_favorite_visible){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
frag_favorite_visible = true;
fragmentTransaction.show(fragment_favorite);
fragmentTransaction.commit();
homeActivity.setTitle("Home");
}
}
});
}
private boolean rundUserSettings(){
if (this.user!=null){
try {
File file = new File(user.getProfile_pic());
Uri uri = Uri.fromFile(file);
ImageView view = (ImageView) findViewById(R.id.imageView_ProfilePic);
view.setImageURI(uri);
}catch (Exception e){
Toast.makeText(Activity_Home.this,"Unable to load profile picture.!",Toast.LENGTH_SHORT).show();
}
return true;
} else {
return false;
}
}
}
The code you're using for adding different fragments on the same activity is really messed up. You can use better approach. I'm adding the sample code below:
In the layout of Activity, add this line of code
<FrameLayout
android:id="#+id/fragBookmarks"
android:layout_weight="2"
android:layout_width="25dp"
android:layout_height="match_parent" />
instead of:
<fragment
android:name="com.nooriandroid.n007.mybookmarks_v1.Fragment_Bookmarks"
android:id="#+id/fragBookmarks"
android:layout_weight="2"
android:layout_width="25dp"
android:layout_height="match_parent" />
Now write this method in your HomeActivity to add different fragments
public void addFragment(Fragment frag, String tag) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragBookmarks, frag, tag);
transaction.addToBackStack(getFragmentManager().getBackStackEntryCount() == 0 ? "FirstFragment" : null).commit();
}
}
This method will help you to add any fragment to this activity on the go. You don't need to add all the fragments from the beginning. Like If now I'm on HomeFragment and I want to open BookmarkFragment on button click from Home, I will write something like;
btnBookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity) getActivity()).addFragment(new BookmarkFragment(), BookmarkFragment.class.getSimpleName()); // This will add the new fragment Bookmark fragment to the activity while adding it to backstack
}
});
Now, If you want to go back from BookmarkFragment to HomeFragment, add this method in your HomeActivity
public void popFragment() {
if (getFragmentManager() == null)
return;
getFragmentManager().popBackStack();
}
And Call this function in BookmarkFragment like,
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity) getActivity()).popFragment(); // This will remove the last added fragment Bookmark fragment
}
});
DrawerLayout should have only two direct children.If you want to replace different fragments in same activity,create a FrameLayout in the app_bar_home layout.Then in your Activity,do this to replace fragments.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frame_layout_id,new yourFragment()).commit();

Categories

Resources