I'm using Android Stduio 2.1. I generated a Navigation Drawer Activity.
How can I call other Activitys or Fragments with the Same Navigation Drawer.
But the Navigation Menu must be still there in every Fragment or Activity I call. How can I manage this?
This is the MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, GPS_Overview2.OnFragmentInteractionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//GPS AN/AUS Überprüfung
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, this.getText(R.string.GPS_AN) , Toast.LENGTH_SHORT).show();
}else{
showGPSDisabledAlertToUser();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//GPS An Message
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(getApplicationContext().getString(R.string.GPS_ERROR))
.setCancelable(false)
.setPositiveButton(getApplicationContext().getString(R.string.GPS_SETTINGS),
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton(getApplicationContext().getString(R.string.cancel),
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#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 onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.gps_overview) {
} else if (id == R.id.tachoscheibe) {
} else if (id == R.id.gps_overview) {
} else if (id == R.id.settings) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.settings) {
} else if (id == R.id.exit) {
System.exit(0);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
This is the activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="false" />
<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>
When you need more information only write a comment.
Greetings form Germany
Tim
Use Intent when to want to go go to another activity
Intent intent = new Intent(CurrentActivity.this,newActivity.class);
And
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.gps_overview) {
startActivity(intent);
} else if (id == R.id.tachoscheibe) {
} else if (id == R.id.gps_overview) {
} else if (id == R.id.settings) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.settings) {
} else if (id == R.id.exit) {
System.exit(0);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
For changing fragment you can you
Fragment fragment = null;
fragmentClass = Fragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_fragment, fragment).commit();
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am creating Navigation drawer activity .I have added one fragment Camera.
When I click in Profile fragment, I got error
" Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference" in this line. MainActivity.onNavigationItemSelected (MainActivity.java:104).
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
Class fragmentClass= null;
if (id == R.id.nav_camera) {
fragmentClass = Camera.class;
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
activitymain.xml
<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" />
<FrameLayout
android:id="#+id/flContent"
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" />
Your Fragment is null, and you are trying to replace that. try
In your Fragment class add this
public static MyFragment newInstance() {
MyFragment myFragment = new MyFragment();
return myFragment;
}
Then do this in your main activity:
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frameLayout,
MyFragment.newInstance()).commit();
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
I have created a Base Activity that contains a navigation drawer.
The drawer will open on slide, but never through the navigation button on the toolbar. I've been stuck on this for quite a while, and I had it working prior to creating this base class and I don't think I've changed anything logically.
I know this question has been asked before, but I've gone through all other similar posts and have not been able to solve it.
Thanks in advance!
public class DrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
protected DrawerLayout drawerLayout;
private ActionBarDrawerToggle toggle;
private Toolbar toolbar;
private NavigationView navigationView;
private boolean enableToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
enableToolbar = true;
}
#Override
public void setContentView(int layoutResID){
super.setContentView(R.layout.activity_drawer);
setToolbar();
setDrawerLayout();
setNavigationDrawer();
setToolbarOnClickListener();
if(!useToolbar())
toolbar.setVisibility(View.GONE);
inflateToContentFrame(layoutResID);
}
public void setUsesToolbar(boolean _enable){
enableToolbar = _enable;
}
private boolean useToolbar(){
return enableToolbar;
}
private void setToolbar(){
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
private void setDrawerLayout(){
drawerLayout = (DrawerLayout)getLayoutInflater().inflate(R.layout.activity_drawer, null);
toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
DrawerActivity.this.invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
DrawerActivity.this.invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
DrawerActivity.this.toolbar.setAlpha(1 - slideOffset / 2);
}
};
toggle.setDrawerIndicatorEnabled(true);
drawerLayout.addDrawerListener(toggle);
drawerLayout.post(new Runnable() {
#Override
public void run() {
toggle.syncState();
}
});
}
private void setNavigationDrawer(){
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void setToolbarOnClickListener(){
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DrawerActivity.this.drawerLayout.openDrawer(GravityCompat.START);
}
});
}
private void inflateToContentFrame(int layoutResID){
FrameLayout content = (FrameLayout) findViewById(R.id.content_frame);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(layoutResID, content, true);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.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.drawer, 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) {
int id = item.getItemId();
Intent _intent;
if (id == R.id.nav_classes) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_appointments) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_clients) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_payments) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if(id == R.id.nav_Settings){
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_share) {
_intent = new Intent(this, AppointmentsActivity.class);
} else if (id == R.id.nav_send) {
_intent = new Intent(this, AppointmentsActivity.class);
}else{
_intent = new Intent(this, AppointmentsActivity.class);
}
drawerLayout.closeDrawer(GravityCompat.START);
startActivity(_intent);
return true;
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<include
layout="#layout/app_bar_drawer"
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_drawer"
app:menu="#menu/activity_drawer_drawer"
/>
</android.support.v4.widget.DrawerLayout>
The DrawerLayout instance you're setting up the Toggle with is not the instance that's on-screen. In the setDrawerLayout() method, you're inflating a new layout that's never used.
Instead of inflating there, use findViewById() to get the DrawerLayout instance that's created and added to the Activity in the super.setContentView() call.
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
Also, you can omit the toolbar.setNavigationOnClickListener() call, as the ActionBarDrawerToggle will set a listener itself, and handle opening and closing the drawer internally.
I am trying to handle NavigationView click listener for back button but it is not working.
navigationView.setOnClickListener may be enough but may be it's due to some other reason that's why added full class
MainActivity.class
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ActionBarDrawerToggle toggle;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
resetActionBar();
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
}
});
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.content_fragment, new CameraFragment()).commit();
}
#Override
public void onBackPressed() {
//super.onBackPressed();
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.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) {
int id = item.getItemId();
if(id == android.R.id.home)
{
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
else
drawerLayout.openDrawer(navigationView);
return true;
}else 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;
if (id == R.id.nav_camera) {
// Handle the camera action
fragment = new CameraFragment();
} else if (id == R.id.nav_gallery) {
fragment = new GalleryFragment();
} else if (id == R.id.nav_slideshow) {
fragment = new SlideShowFragment();
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if(fragment!=null){
if(item.isChecked())
{
if(getSupportFragmentManager().getBackStackEntryCount()==0){
drawer.closeDrawers();
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.content_fragment, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.content_fragment, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void removeAllFragments(){
getSupportFragmentManager().popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
public void replaceFragment(final Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.content_fragment, fragment).addToBackStack("")
.commit();
}
public void updateDrawerIcon() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
Log.i("", "BackStackCount: " + getSupportFragmentManager().getBackStackEntryCount());
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
toggle.setDrawerIndicatorEnabled(false);
else
toggle.setDrawerIndicatorEnabled(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, 50);
}
public void resetActionBar()
{
//display home
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
Answer found by Mike M Comment:
remove navigation.setOnClickListener and replace it to
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
}
});
My main activity consists of a navigation drawer and switching between fragments was working fine. Now i tried to implement Material Searchview using this library which requires the toolbar to be set last inside the xml file. So now my serachview is working fine but onNavigationItemSelected stops working and i cant switch between fragments. If inside the xml i write navigation drawer below the toolbar navigation starts working again but searchview stops working. Please help me.
activity_home.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
/>
<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.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
/>
<com.miguelcatalan.materialsearchview.MaterialSearchView
android:id="#+id/search_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</FrameLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.DrawerLayout>
HomeActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
exploreFragment();
searchView = (MaterialSearchView) findViewById(R.id.search_view);
searchView.setVoiceSearch(false);
searchView.setCursorDrawable(R.drawable.custom_cursor);
searchView.setEllipsize(true);
// searchView.setSuggestions(getResources().getStringArray(R.array.query_suggestions));
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(HomeActivity.this,query,Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//Do some magic
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home,menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
exploreFragment();
} else if (id == R.id.nav_gallery) {
newFragment();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void exploreFragment(){
fragment = new ExploreFragment();
Bundle bundle = new Bundle();
// bundle.putString("loginToken",loginToken);
// bundle.putString("userId", userId);
fragment.setArguments(bundle);
if (fragment != null) {
getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
}
}
public void newFragment(){
fragment = new NewFragment();
Bundle bundle = new Bundle();
// bundle.putString("loginToken",loginToken);
// bundle.putString("userId", userId);
fragment.setArguments(bundle);
if (fragment != null) {
getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
}
}
I think you forgot to add actionviewclass
<item
android:id="#+id/action_search"
android:icon="#drawable/ic_search"
android:title="Search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="com.miguelcatalan.materialsearchview.MaterialSearchView" />
I'm trying to use FAB with navigation drawer and fragment content that changes with onitemClcik() in navigation menu
but after I was clicked on any item and do replace() fragment I have get bank screen
class :
public class SubTaB extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener , ObservableScrollViewCallbacks {
#Bind(R.id.list_view)
ObservableListView mObservableListView;
#Bind(R.id.fabtoolbar)
FabToolbar mFabToolbar;
#Bind(R.id.fab)
android.support.design.widget.FloatingActionButton mFab;
#Bind(R.id.ic_call)
ImageView mIcCall;
#Bind(R.id.ic_email)
ImageView mIcEmail;
#Bind(R.id.ic_forum)
ImageView mIcForum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_ta_b);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ButterKnife.bind(this);
initListView();
mFabToolbar.setFab(mFab);
}
private void initListView() {
List<String> list = new ArrayList<String>(100);
for (int i = 0; i < 100; i++) {
list.add("Item " + i);
}
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1, list);
// mObservableListView.setAdapter(adapter);
mObservableListView.setScrollViewCallbacks(this);
}
#Override
public void onScrollChanged(int i, boolean b, boolean b1) {
}
#Override
public void onDownMotionEvent() {
}
#Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
Log.d("","Scroll scroll scroll");
if (scrollState == ScrollState.UP) {
mFabToolbar.slideOutFab();
} else if (scrollState == ScrollState.DOWN) {
mFabToolbar.slideInFab();
}
}
#OnClick(R.id.fab)
void onFabClick() {
mFabToolbar.expandFab();
}
#OnClick(R.id.call)
void onClickCall() {
iconAnim(mIcCall);
}
#OnClick(R.id.ic_email)
void onClickEmail() {
iconAnim(mIcEmail);
}
#OnClick(R.id.ic_forum)
void onClickForum() {
iconAnim(mIcForum);
}
private void iconAnim(View icon) {
Animator iconAnim = ObjectAnimator.ofPropertyValuesHolder(
icon,
PropertyValuesHolder.ofFloat("scaleX", 1f, 1.5f, 1f),
PropertyValuesHolder.ofFloat("scaleY", 1f, 1.5f, 1f));
iconAnim.start();
}
///////////////////////////////////////
#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.sub_ta_b, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// mFabToolbar.slideOutFab();
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment newFragment= null;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//
if (id == R.id.nav_camera) {
newFragment = new OneFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, newFragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_gallery) {
newFragment = new DashDetails();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack("TAG");
transaction.commit();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
XML layot :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/fragment_container2"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/MyMaterialTheme.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/MyMaterialTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:id="#+id/fragment_container"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
layout="#layout/FAB" />
</LinearLayout>
<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_sub_ta_b"
app:menu="#menu/activity_sub_ta_b_drawer" />
Your activity layout is a bit odd. You should have a root parent layout like for example CoordinatorLayout.
Your XML layout however does not have a root layout, the LinearLayouts are all siblings.
Another thing I noticed is that the LinearLayout around the FAB is the one you replace when replacing your fragment. This is wrong. Remove LinearLayout around the FAB and add a FrameLayout with id=fragment_container.
The layout structure could look like this
<CoordinatorLayout>
<AppBarLayout>
<Toolbar/>
//... other layouts here
</AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"/>
//... rest of your layout here
<FloatingActionButton android:gravity="bottom|end" />
</CoordinatorLayout>