I have used Navigation Drawer, Bottom Navigation bar, and a custom Action bar.
Bottom navigation bar and action bar are working fine. The navigation drawer also shows a menu present under it but the items are not clickable.
I have tried all the answers related to
but still, my problem has not been solved yet. there is no error in the debug section.
Navigation Drawer Image
MainActivity Image
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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/nav_host_fragment_activity_main"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
android:clickable="false"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#id/bottomNavigationView"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
app:navGraph="#navigation/mobile_navigation" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#color/white"
android:backgroundTint="#color/colorAccent"
android:focusableInTouchMode="true"
android:orientation="horizontal"
app:itemHorizontalTranslationEnabled="false"
app:itemIconTint="#color/purple_500"
app:itemTextAppearanceActive="#style/MaterialAlertDialog.MaterialComponents.Title.Panel"
app:itemTextColor="#3F51B5"
app:labelVisibilityMode="labeled"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/nav_host_fragment_activity_main"
app:menu="#menu/bottom_nav_menu" />
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorAccent"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:popupTheme="#style/Theme.PathShalaInstitute.PopupOverlay" />
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header_navigation_drawer"
app:menu="#menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
Menu XML
<?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="none">
<item
android:id="#+id/navigation_home"
android:checked="true"
android:icon="#drawable/home"
android:title="#string/menu_home" />
<item
android:id="#+id/nav_video"
android:icon="#drawable/ic_menu_gallery"
android:title="#string/menu_video" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/menu_slideshow" />
<item
android:id="#+id/nav_logOut"
android:icon="#drawable/log_out"
android:title="#string/log_out" />
</group>
<item android:title="Upcoming">
<menu>
<item
android:id="#+id/soon"
android:title="Coming Soon" />
</menu>
</item>
</menu>
MainActivity Java
package com.laksyaindia.pathshala;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.Toolbar;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
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;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.laksyaindia.pathshala.databinding.ActivityMainBinding;
import com.laksyaindia.pathshala.hamburger.ui.videos.VideosFragment;
import java.util.Objects;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private ActivityMainBinding binding;
private DrawerLayout drawer;
private NavController navController;
private NavigationView navigationView;
private BottomNavigationView bottomNavigationView;
private AppBarConfiguration appBarConfiguration;
private ActionBarDrawerToggle toggle;
FirebaseAuth auth;
FirebaseDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
database = FirebaseDatabase.getInstance();
auth = FirebaseAuth.getInstance();
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
drawer = binding.drawerLayout;
navigationView = binding.navigationView;
bottomNavigationView = binding.bottomNavigationView;
Toolbar toolbar = binding.toolbar;
setSupportActionBar(toolbar);
navigationView.bringToFront();
toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
drawer.addDrawerListener(toggle);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.navigation_home);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home,
R.id.navigation_test,
R.id.navigation_batches,
R.id.navigation_feed)
.setDrawerLayout(drawer)
.build();
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
NavigationUI.setupWithNavController(bottomNavigationView, navController);
View headerView = navigationView.getHeaderView(0);
TextView user = headerView.findViewById(R.id.name);
TextView gmail = headerView.findViewById(R.id.gmail);
database.getReference().child("Users").child((Objects.requireNonNull(FirebaseAuth.getInstance().getUid())))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String name = Objects.requireNonNull(snapshot.child("username").getValue()).toString();
String email = Objects.requireNonNull(snapshot.child("mail").getValue()).toString();
user.setText("Hello ! " + name);
gmail.setText(email);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START))
drawer.closeDrawer(GravityCompat.START);
else
super.onBackPressed();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item){
int itemId = item.getItemId();
if (itemId == R.id.navigation_home) {
Toast.makeText(MainActivity.this, "You have selected Home...", Toast.LENGTH_SHORT).show();
}
else if (itemId == R.id.nav_video) {
//getSupportFragmentManager().beginTransaction().replace(R.id.navigation_home, new VideosFragment()).commit();
Toast.makeText(MainActivity.this, "You have selected Video...", Toast.LENGTH_SHORT).show();
}
else if (itemId == R.id.nav_slideshow) {
Toast.makeText(this, "Slideshow...", Toast.LENGTH_SHORT).show();
return true;
}
else if (itemId == R.id.nav_logOut) {
auth.signOut();
Intent logOut = new Intent(MainActivity.this, SignInActivity.class);
startActivity(logOut);
finish();
Toast.makeText(MainActivity.this, "You have been logged out successfully", Toast.LENGTH_SHORT).show();
return true;
}
else if (itemId == R.id.soon) {
Toast.makeText(MainActivity.this, "Coming soon...", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Related
i am having a serious weird bug in android navigation view item click, the items are only clicking once when you open the app and stops clicking after, but the weirdest part is that the item is responding to click at the edge every time.
Below is my main xml code
<?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:layoutDirection="ltr"
tools:openDrawer="start">
<include layout="#layout/layout_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<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"
android:theme="#style/NavigationView"
app:itemTextColor="#color/black"
app:itemIconTint="#color/black"
android:background="#color/white"
app:headerLayout="#layout/nav_header_main"
android:elevation="5dp"
app:menu="#menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
Navigation menu items
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:checked="true"
android:id="#+id/home"
android:icon="#drawable/ic_home"
android:title="#string/home" />
<item
android:id="#+id/latest"
android:icon="#drawable/ic_latest"
android:title="#string/latest" />
<item
android:id="#+id/category"
android:icon="#drawable/ic_category"
android:title="#string/category" />
</group>
</menu>
The layout Frame
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_height="wrap_content"
android:layout_width="match_parent"
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="#color/toolbar"
android:theme="#style/AppTheme.AppBarOverlay"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:layout_marginTop="55dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/frame_one"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
My Activity code
package com.education.books.MySchoolLibrary;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
public class NewAct extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
public Toolbar toolbar;
private ProgressBar progressBar;
private DrawerLayout drawer;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Tool");
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();
this.navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerview = navigationView.getHeaderView(0);
findViewById(R.id.frame_one).setOnClickListener(v -> {
Toast.makeText(this, "frame ti ya werey!!!", Toast.LENGTH_SHORT).show();
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
drawer.closeDrawers();
if (id == R.id.home) {
Toast.makeText(this, "clicked", Toast.LENGTH_SHORT).show();
} else if (id == R.id.latest) {
Toast.makeText(this, "clicked", Toast.LENGTH_SHORT).show();
} else if (id == R.id.category) {
Toast.makeText(this, "clicked", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "clicked", Toast.LENGTH_SHORT).show();
}
return true;
}
}
But if i copy this whole code into an entirely new application, it is working fine, pls i don't know what i am doing wrong. Thanks.
I am also facing same issue.found a work around solution like below
nav_view.menu.findItem(R.id.menu_share).setOnMenuItemClickListener {
shareApp()
drawer_layout.closeDrawer(GravityCompat.START)
true
}
I am trying to learn coding in Android Studio but I am having trouble with the activities.
I have a google map code that I was to add to the navigation drawer but I can't because the error always says MapsActivity cannot be cast to androidx.fragment.app.Fragment
here is my MapActivity.Java
package ***.***.***.ui.map;
import androidx.fragment.app.FragmentActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private Object LocationServices;
GoogleMap mMap;
private GoogleMap.OnCameraIdleListener onCameraIdleListener;
private TextView resutText;
#Override
public void onResume() {
super.onResume();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(***.***.***.R.id.map);
mapFragment.getMapAsync(this);
resutText = (TextView) findViewById(***.***.***.R.id.dragg_result);
configureCameraIdle();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnCameraIdleListener(onCameraIdleListener);
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
String locationProvider = LocationManager.NETWORK_PROVIDER;
#SuppressLint("MissingPermission") android.location.Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
double userLat = lastKnownLocation.getLatitude();
double userLong = lastKnownLocation.getLongitude();
LatLng user = new LatLng(userLat, userLong);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(userLat, userLong), 16.0f));
}
private void configureCameraIdle() {
onCameraIdleListener = new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
LatLng latLng = mMap.getCameraPosition().target;
Geocoder geocoder = new Geocoder(MapsActivity.this);
try {
List<Address> addressList = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addressList != null && addressList.size() > 0) {
String locality = addressList.get(0).getAddressLine(0);
String country = addressList.get(0).getCountryName();
if (!locality.isEmpty() && !country.isEmpty())
resutText.setText(locality + " " + country);
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
protected void setStatusBarTranslucent(boolean makeTranslucent) {
if (makeTranslucent) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
}
and the activity_maps.xml
<?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"
android:orientation="vertical">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity" />
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="172dp"
android:layout_marginTop="310dp"
android:layout_marginEnd="172dp"
android:layout_marginBottom="356dp"
android:adjustViewBounds="true"
android:maxWidth="65dp"
android:maxHeight="65dp"
android:src="#drawable/car_pin" />
<!-- Implementation of find my location button -->
<TextView
android:id="#+id/dragg_result"
android:layout_width="260dp"
android:layout_height="84dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="75dp"
android:layout_marginTop="74dp"
android:layout_marginEnd="75dp"
android:layout_marginBottom="572dp"
android:text="TextView" />
<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" />
</RelativeLayout>
Also the MainActivity.java
package ***.***.***;
import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_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.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();
}
}
What can I do to make it work without redoing all of the code, thanks in advance.
I am not quite sure, but I think you have to put your <framgent> inside a <FramgeLayout> in your xml file like this:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/mapfragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment"/>
<!-- other components -->
<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" />
</FrameLayout>
it is possible that your imports are wrong. Does it work if you import this in your java class android.support.v4.app.FragmentActivity instead of androidx.fragment.app.FragmentActivity? I think the error is in the imports than
I'm a beginner in android development, I'm creating a simple web app, and I have this menu/drawer that contains 100 strings/entries, but I can't swipe down, I think I erase something from the code but don't know what. Here is a pic and here is the code from active_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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<WebView
android:id="#+id/activity_main_webview"
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" />
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.drawerlayout.widget.DrawerLayout>
and MainActivity.java
package com.example.psalms;
import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("file:///android_asset/index.html");
}
#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();
}
}
Thanks in advance!
Just remove the web view from this activity_main.xml and place it inside somewhere #layout/app_bar_main or inside Content_main.xml and move the include tag above Navigation view.It will solve your problem.
<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" />
I made this switch on one of my fragment to switch from the dark theme to light theme. The only problem is that when I leave fragment with the switch on when I go back to the fragment, the switch is off instead of being on like I left it.
Here are the images.
When I go on the fragment: Fragment Switch Off
When I flip the switch: Fragment Switch On
Then I leave the Fragment, then come back to the Fragment: Fragment Switch off while supposed to be on
Her is my code:
SettingsFragment.java:
package com.barzalou.lpapineau.test.ui.settings;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProviders;
import com.barzalou.lpapineau.test.R;
import com.barzalou.lpapineau.test.ui.CheckedChangeCallback;
import java.util.Objects;
public class SettingsFragment extends Fragment {
private SettingsViewModel settingsViewModel;
private CheckedChangeCallback callback = null;
public void onAttach(final Activity activity) {
super.onAttach(activity);
if (activity instanceof CheckedChangeCallback) {
this.callback = (CheckedChangeCallback) activity;
}
}
public void onDetach() {
super.onDetach();
callback = null;
}
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
settingsViewModel = ViewModelProviders.of(this).get(SettingsViewModel.class);
View root = inflater.inflate(R.layout.fragment_settings, container, false);
final TextView textView = root.findViewById(R.id.text_settings);
settingsViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final Switch DarkMode = (Switch) getView().findViewById(R.id.DarkModeSwitch);
final boolean DarkModeVal = DarkMode.isChecked();
Log.d("Dark Mode Checked Value", String.valueOf(DarkModeVal));
DarkMode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
callback.onCheckedChange(isChecked);
}
});
}
}
SettingsViewModel.java:
package com.barzalou.lpapineau.test.ui.settings;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class SettingsViewModel extends ViewModel {
private MutableLiveData<String> mText;
public SettingsViewModel() {
mText = new MutableLiveData<>();
mText.setValue("Settings");
}
public LiveData<String> getText() {
return mText;
}
}
CheckedChangeCallback.java:
package com.barzalou.lpapineau.test.ui;
public interface CheckedChangeCallback {
void onCheckedChange(boolean isChecked);
}
MainActivity.java:
package com.barzalou.lpapineau.test;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.audiofx.Equalizer;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.Switch;
import com.barzalou.lpapineau.test.ui.CheckedChangeCallback;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity implements CheckedChangeCallback {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_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.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 onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_exit) {
finish();
System.exit(0);
}
return false;
}
public void onCheckedChange(boolean isChecked) {
Switch DarkMode = findViewById(R.id.DarkModeSwitch);
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
Log.d("Dark Mode Switch State", "On");
DarkMode.setChecked(true);
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
Log.d("Dark Mode Switch State", "Off");
DarkMode.setChecked(false);
}
}
}
fragment_settings.xml:
<?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:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#fff"
android:padding="10dp"
tools:context=".ui.home.HomeFragment">
<!-- Title -->
<TextView
android:id="#+id/text_settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:shadowColor="#bfbfbf"
android:shadowDx="5"
android:shadowDy="5"
android:shadowRadius="0.01"
android:text="#string/this_is_home"
android:textAlignment="center"
android:textColor="#000"
android:textSize="34sp" />
<!-- ...... -->
<!-- Card_View Settings -->
<androidx.cardview.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view_outer"
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_gravity="center"
android:translationY="60dp"
android:layout_marginLeft="3dp"
android:layout_marginStart="3dp"
android:layout_marginTop="3dp"
card_view:cardBackgroundColor="#d3d3d3"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="0dp" />
<androidx.cardview.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view_inner"
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_gravity="center"
android:translationY="60dp"
android:layout_marginRight="3dp"
android:layout_marginEnd="3dp"
card_view:cardBackgroundColor="#f5f5f5"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="3dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
android:elevation="4dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="#string/Settings"
android:textSize="22sp"/>
<Switch
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:id="#+id/DarkModeSwitch"
android:text="#string/dark_mode"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
<!-- .................. -->
<!-- Card_View 2 -->
<androidx.cardview.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view_1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center"
android:translationY="170dp"
android:layout_marginRight="3dp"
android:layout_marginEnd="3dp"
card_view:cardBackgroundColor="#f5f5f5"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="3dp" />
<androidx.cardview.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view_2"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center"
android:translationY="170dp"
android:layout_marginLeft="3dp"
android:layout_marginStart="3dp"
android:layout_marginTop="3dp"
card_view:cardBackgroundColor="#d3d3d3"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="0dp" >
</androidx.cardview.widget.CardView>
<!-- ........... -->
</RelativeLayout>
How can this be fixed? I want it to stay flipped while the dark theme is on.
Thanks!
Because fragment recreated, the switch result is lost. So you should save the switch result. For example, SharedPreference.
I am trying to open my NavigationDrawer which I created in my MainActivity in my HomeFragment by clicking on an Icon. When I click on the Icon I want the drawer to open... Can this be done even though, I have it in my MainActivity file and NOT my HomeFragment?
Below you have my fragment_home.xml file and HomeFragment.java
MainActivity.java
package com.e.events;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;
import com.e.events.Fragment.HomeFragment;
import com.e.events.Fragment.NotificationsFragment;
import com.e.events.Fragment.ProfileFragment;
import com.e.events.Fragment.SaveFragment;
import com.e.events.Fragment.SearchFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity implements DrawerLocker, NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
BottomNavigationView bottomNavigationView;
Fragment selectedFragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
Bundle intent = getIntent().getExtras();
if (intent != null) {
String publisher = intent.getString("publisherid");
SharedPreferences.Editor editor = getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("profileid", publisher);
editor.apply();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
} else {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.nav_edit_profile:
Intent editProfile = new Intent(MainActivity.this, EditProfileActivity.class);
startActivity(editProfile);
break;
case R.id.nav_settings:
Intent settings = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(settings);
break;
case R.id.nav_logout:
Intent logout = new Intent(MainActivity.this, StartActivity.class);
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(MainActivity.this, StartActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_edit_profile) {
return true;
}
return super.onOptionsItemSelected(item);
}
private BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_search:
selectedFragment = new SearchFragment();
break;
case R.id.nav_notifications:
selectedFragment = new NotificationsFragment();
break;
case R.id.nav_profile:
SharedPreferences.Editor editor = getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("profileid", FirebaseAuth.getInstance().getCurrentUser().getUid());
editor.apply();
selectedFragment = new ProfileFragment();
break;
case R.id.nav_save:
selectedFragment = new SaveFragment();
break;
}
if (selectedFragment != null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
}
return true;
}
};
public void setDrawerLocked(boolean enabled){
if(enabled){
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}else{
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
}
}
fragment_home.xml
<?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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".Fragment.HomeFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar_home_fragment"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?android:attr/windowBackground"
android:elevation="4dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/events_logo_main_activity"
android:layout_width="180dp"
android:layout_height="45dp"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:src="#drawable/events_logo_black_max_size" />
<ImageView
android:id="#+id/camera_create_an_event_main_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerInParent="true"
android:layout_marginEnd="11dp"
android:src="#drawable/ic_camera_create_events_home_fragment_black" />
<ImageView
android:id="#+id/three_bars_settings_main_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerInParent="true"
android:src="#drawable/ic_three_bars_settings_home_fragment_black" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/bar">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
<ProgressBar
android:id="#+id/progress_circular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
HomeFragment
package com.e.events.Fragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.e.events.Adapter.PostAdapter;
import com.e.events.EditProfileActivity;
import com.e.events.MainActivity;
import com.e.events.Model.Post;
import com.e.events.OptionsActivity;
import com.e.events.PostActivity;
import com.e.events.R;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class HomeFragment extends Fragment {
ImageView options;
DrawerLayout drawer;
ProgressBar progressBar;
private RecyclerView recyclerView;
private PostAdapter postAdapter;
private List<Post> postLists;
private ImageView camera_create_event;
private List<String> followingList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
postLists = new ArrayList<>();
postAdapter = new PostAdapter(getContext(), postLists);
recyclerView.setAdapter(postAdapter);
progressBar = view.findViewById(R.id.progress_circular);
drawer = view.findViewById(R.id.nav_view);
Toolbar toolbar = view.findViewById(R.id.toolbar_home_fragment);
options = view.findViewById(R.id.three_bars_settings_main_activity);
options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
camera_create_event = view.findViewById(R.id.camera_create_an_event_main_activity);
camera_create_event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PostActivity.class);
startActivity(intent);
}
});
checkFollowing();
return view;
}
private void checkFollowing() {
followingList = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Follow")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child("following");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
followingList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
followingList.add(snapshot.getKey());
}
readPosts();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readPosts() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postLists.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Post post = snapshot.getValue(Post.class);
for (String id : followingList) {
if (post.getPublisher().equals(id)) {
postLists.add(post);
}
}
}
postAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Logcat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.e.events, PID: 18229
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.drawerlayout.widget.DrawerLayout.openDrawer(int)' on a null object reference
at com.e.events.Fragment.HomeFragment$1.onClick(HomeFragment.java:85)
at android.view.View.performClick(View.java:6663)
at android.view.View.performClickInternal(View.java:6635)
at android.view.View.access$3100(View.java:794)
at android.view.View$PerformClick.run(View.java:26199)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
you don't have any DrawerLayout in your fragment_home.xml try to change your RelativeLayout to DrawerLayout :
<?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"
tools:context=".Fragment.HomeFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar_home_fragment"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?android:attr/windowBackground"
android:elevation="4dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/events_logo_main_activity"
android:layout_width="180dp"
android:layout_height="45dp"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:src="#drawable/events_logo_black_max_size" />
<ImageView
android:id="#+id/camera_create_an_event_main_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerInParent="true"
android:layout_marginEnd="11dp"
android:src="#drawable/ic_camera_create_events_home_fragment_black" />
<ImageView
android:id="#+id/three_bars_settings_main_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerInParent="true"
android:src="#drawable/ic_three_bars_settings_home_fragment_black" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/bar">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
<ProgressBar
android:id="#+id/progress_circular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</androidx.drawerlayout.widget.DrawerLayout>
if you want to open drawer layout of your activity from your fragment then add this code in your fragment:
Activity mActivity;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
if (context instanceof Activity) {
mActivity = (Activity) context;
}
}
get your drawer layout in your fragment as:
DrawerLayout drawer = mActivity.findViewById(R.id.drawer_layout);
now you can open or close your drawer layout from your activity
yourImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//open or close your drawer according to your need
}
});