Android Navigation Drawer with multiple Activity - android

I am trying to create a BaseActivity with navigation drawer and extend it in other activities so that I can reuse the the navigation drawer code.
What I have figured out so far:
I can use fragments to do this (which I can do).
I can use a BaseActivity and inflate the content area (Frame layout with id as “main_container” in my case) to show other activities. In this case I have figured out how to click on navigation drawer items to change activity.
However, when I have a button inside one of my activity (example activityA) and I want to load another activity (activityB), show a toast, etc. by clicking that button, the click listener does not work unless I write the code for the listener inside the onCreate method of the BaseActivity.
To me this does not make sense because it forces me to write all the codes inside the BaseActivity which is not the most efficient way of writing code (the activities acts like fragments so I can just use fragments instead).
What I want to know is, how to load the navigation drawer on all activities extending the BaseActivity, and still allow the activities to retain their behaviours.
Code samples
My activity_home.xml (BaseActivity)
<?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"
android:id="#+id/drawer_layout"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeActivity"
tools:openDrawer="start"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/custom_tool"
layout="#layout/custom_bar"/>
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/nav_display"
app:menu="#menu/nav_drawer_menu"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"/>
</android.support.v4.widget.DrawerLayout>
activity_main.xml (activityA)
<?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"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="0dp"
android:layout_height="147dp"
android:layout_marginStart="105dp"
android:layout_marginLeft="105dp"
android:layout_marginTop="150dp"
android:layout_marginEnd="105dp"
android:layout_marginRight="105dp"
android:layout_marginBottom="48dp"
android:contentDescription="#string/app_logo"
app:layout_constraintBottom_toTopOf="#+id/search_bar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
app:srcCompat="#mipmap/ic_launcher" />
<SearchView
android:id="#+id/search_bar"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_marginStart="50dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="48dp"
android:layout_marginEnd="50dp"
android:layout_marginRight="50dp"
android:layout_marginBottom="50dp"
android:background="#drawable/input_default"
android:gravity="center"
app:layout_constraintBottom_toTopOf="#+id/search_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView" />
<Button
android:id="#+id/search_button"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_marginStart="150dp"
android:layout_marginLeft="150dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="150dp"
android:layout_marginRight="150dp"
android:layout_marginBottom="228dp"
android:background="#drawable/button_default"
android:text="#string/search"
android:textColor="#color/colorAccent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/search_bar" />
</android.support.constraint.ConstraintLayout>
When the app is initially loading the “main_content” of the BaseActivity is inflated with the activity_main layout.
When I clicked the search_button inside the activity_main.xml, I want to load another activity which is only happening when I am writing the code inside the base activity.
HomeActivity
package com.example.naisse;
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.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;
public class HomeActivity extends AppCompatActivity {
protected static int position;
private DrawerLayout drawer;
protected FrameLayout frames;
Button searchButton;
/**
* This flag is used just to check that launcher activity is called first time
* so that we can open appropriate Activity on launch and make list item position selected accordingly.
* */
private static boolean isLaunch = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.custom_tool);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
frames = findViewById(R.id.main_container);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
/*inflating the layout with activity_main*/
getLayoutInflater().inflate(R.layout.activity_main, frames);
searchButton = findViewById(R.id.search_button);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*removing the activity_main and inflating they layout with activity_result*/
frames.removeAllViews();
getLayoutInflater().inflate(R.layout.activity_result, frames);
}
});
}
#Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
super.onBackPressed();
}
}
}
Extending MainActivity with HomeActivity
MainActivity
package com.example.naisse;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends HomeActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
How to solve this issue?

I am surprised so few are interested in doing this in all these years. Maintaining the duplicated code of the DrawerLayout stuff in xml files of all activities is pretty silly.
I tried the self-answer from #Mill3r, unfortunately overriding setContentView conflicts with databinding and causes crash.
Instead of setContentView I create a method in the base activity like:
public void setContent(View contentView) {
// Find the content container
frames = findViewById(R.id.main_container);
frames.removeAllViews();
frames.addView(contentView);
// The rest of the base setup
Toolbar toolbar = findViewById(R.id.custom_tool);
setSupportActionBar(toolbar);
drawer = 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();
}
Then in all activities derided from the base, call this function after setting databinding, like:
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
setContent(binding.getRoot());

For answer and understanding, please read the discussion between me and Mike M.
What I was initially doing was inflating the "main_container" with layout and therefore the Activity class was not getting triggered. To do that, I had to override setContentView() method inside the BaseActivity (HomeActivity in my case) and put every sharable code such as toolbar and navigation drawer inside that.
My new HomeActivity.class
public class HomeActivity extends AppCompatActivity {
private DrawerLayout drawer;
protected FrameLayout frames;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
#Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
super.onBackPressed();
}
}
#Override
public void setContentView(int layoutResID) {
// Set the base layout
super.setContentView(R.layout.activity_home);
// Find the content container
frames = findViewById(R.id.main_container);
// Inflate the extending Activity's layout into it
getLayoutInflater().inflate(layoutResID, frames);
// The rest of the base setup
Toolbar toolbar = findViewById(R.id.custom_tool);
setSupportActionBar(toolbar);
drawer = 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();
}
}
And now the toolbar and navigation drawer is shared across all activities.

Related

Navigation menu and add button on selective fragments in android

I need your help to understand the concept of menu in android.
I am using a navigation menu(bar) in android and load it on the MainActivity and put three different fragments.
On app start the navigation menu opened and default fragment also loaded as mentioned below.
Here everything is ok, but when i click on the third menu option (Credit Cards) then a fragment opened in that fragment, i am using ListView as mentioned below:
Now i want the add button on the bar, here you can see its below the bar.
How i can achive this? please help me out. Here i want the burger icon for navigation at left side and add icon/button at right side on same bar.
Note: I tried to add the button on the toolbar i am using inside the DrawerLayout but this button appears on all the fragments.
Here is the code for activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.ac xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/drawer_layout"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:id="#+id/toolbar"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
>
</android.support.v7.widget.Toolbar>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragement_container"/>
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu" >
</android.support.design.widget.NavigationView>
</android.support.v4.widget.ac>
MainActivity.java
package com.mas.mas;
import android.os.Bundle;
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.MenuItem;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.nagivation_drawer_open, R.string.nagivation_drawer_close);
drawerLayout.addDrawerListener(drawerToggle);
drawerToggle.syncState();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container, new TransactionsListFragment()).commit();
setTitle("Transactions");
navigationView.setCheckedItem(R.id.transactions);
}
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.transactions:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container, new TransactionsListFragment()).commit();
setTitle("Email");
break;
case R.id.banks:
// getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container, new MessageFragement()).commit();
setTitle("Banks");
break;
case R.id.cards:
setTitle("Cards");
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container, new CardsFragment()).commit();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
Thanks.
Add button in tool bar in mainActivity
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/adimage"
android:layout_marginBottom="#dimen/padd_10"
android:layout_marginTop="#dimen/padd_10"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ad"></ImageView>
</RelativeLayout>
then use this for onClick Listner In mainActivity.java
Toolbar toolbar = findViewById(R.id.toolbar);
adsImageView=toolbar.findViewById(R.id.adimage);
adsImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
hope it helps

Action Bar is not visible?

In my android application,I am having a drawer but in order to get the drawer i have to manually click and drag that drawer. How can i add the symbol to my tool bar? ( by clicking that i want to handle my drawer ) Also how can i make that toolbar visible in the all other layouts as well?
Here is my activity_drawer.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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer"
tools:context=".drawer">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:minHeight="?android:attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar" />
<android.support.design.widget.NavigationView
app:headerLayout="#layout/header_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
app:itemTextColor="#color/grey"
app:itemIconTint="#color/grey"
app:menu="#menu/menudrawer"
android:layout_gravity="start">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
here is my drawer.java
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class drawer extends AppCompatActivity {
private DrawerLayout mDrawer;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer);
mDrawer = (DrawerLayout) findViewById(R.id.drawer);
mToggle = new ActionBarDrawerToggle(this,mDrawer,R.string.Open,R.string.Close);
mDrawer.addDrawerListener(mToggle);
mToggle.syncState();
Toolbar toolbar = findViewById(R.id.toolbar);
if (getSupportActionBar()!=null){
setSupportActionBar(toolbar);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
Try with this version of action bar drawer toggle
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
For the question about toolbar, you need to change this:
if (getSupportActionBar()!=null){
setSupportActionBar(toolbar);
}
to just this:
setSupportActionBar(toolbar);
and it should work.
About propagating this behavior on the other screens - you either need to:
Add the toolbar and drawer everywhere
or
Have this as a base layout in base activity
and inherit from base activity, adding proper layouts on children
Use below code it helping you according to your need :
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.str_drawer_o, R.string.str_drawer_clos)
if (getSupportActionBar()!=null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_nav_icon, this.getTheme());
actionBarDrawerToggle.setHomeAsUpIndicator(drawable);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
});
actionBarDrawerToggle.syncState();

How can I implement my custom toolbar in my Fragment

I read so much article and watched so many videos but I still don't know, how to set up an action bar in an Fragment. I have a activity X with an custom toolbar and one navigation view on the top left(the toolbar is separated in an xml file), I import it in the xml for the activity X.
Here is my toolbar in one single 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/drawerChooser"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/new_gradients"
android:fitsSystemWindows="true"
tools:context=".ChoosingActivity">
<!--tools:openDrawer="start"-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</LinearLayout>
<FrameLayout
android:id="#+id/fragment_container_toolbar"
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"
app:headerLayout="#layout/header"
app:menu="#menu/drawer_menu">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
EDIT, new toolbar:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#drawable/new_gradients"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/new_gradients"
android:fitsSystemWindows="true"
tools:context=".ChoosingActivity">
<FrameLayout
android:id="#+id/fragment_container_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer_menu">
</android.support.design.widget.NavigationView>
</LinearLayout>
</LinearLayout>
Here is my activity X:
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.support.annotation.NonNull;
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.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class ChoosingActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
public void userChoosed(View view) {
Intent choosedIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(choosedIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choosing);
Toolbar toolbar = findViewById(R.id.toolbarxml);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawerChooser);
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();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Item will be Selected
switch (item.getItemId()) {
case R.id.nav_meetings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Ausstehende_Treffen_Fragment()).commit();
break;
case R.id.nav_finished_meetings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Abgeschlossene_Treffen_Fragment()).commit();
break;
case R.id.nav_rate:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Treffen_Bewerten_Fragment()).commit();
break;
case R.id.nav_edit_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Profil_Bearbeiten_Fragment()).commit();
break;
case R.id.nav_settings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Einstellungen_Fragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
EDIT, new activity X ( look at my comment "Toolbar_chooser or toolbar"):
public class ChoosingActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
public void userChoosed(View view) {
Intent choosedIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(choosedIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choosing);
Toolbar toolbar = findViewById(R.id.toolbar_chooser); // Toolbar_chooser or toolbar?
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawerChooser);
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();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Item will be Selected
switch (item.getItemId()) {
case R.id.nav_meetings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Ausstehende_Treffen_Fragment()).commit();
break;
case R.id.nav_finished_meetings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Abgeschlossene_Treffen_Fragment()).commit();
break;
case R.id.nav_rate:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Treffen_Bewerten_Fragment()).commit();
break;
case R.id.nav_edit_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Profil_Bearbeiten_Fragment()).commit();
break;
case R.id.nav_settings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Einstellungen_Fragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
And here my Fragment where I want to add the toolbar with the navigation view:
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
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.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class Ausstehende_Treffen_Fragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_ausstehende_treffen,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar(toolbar); // HOW???
}
}
EDIT, new Fragment:
public class Ausstehende_Treffen_Fragment extends Fragment {
// Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbarreal);
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_ausstehende_treffen,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = ((ChoosingActivity)getActivity()).findViewById(R.id.toolbar_ausstehende_treffen);
}
}
Here is also my xml for the fragment, where I want to have the toolbar:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_orange_light">
<include
android:id="#+id/toolbar_ausstehende_treffen"
layout= "#layout/toolbar"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ausstehende Treffen Fragment"
android:textSize="25sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
Im not able anymore to open my navigation bar in my choosing activity and I don't know why..
I include the toolbars manually in the xml files, its necessary right? + some code in the fragment itself. Man I hope you understand my code and my problems. Pls help me I just want to keep my custom toolbar in any fragment and activity.
Pls help me, its so frustrating, waste so many hours for just a toolbar, which already exists..
Try adding toolbar in you activity :
mTopToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(mTopToolbar);
Get the Activity that owns the fragment (Fragment.getActivity()) and set its ActionBar property.
Then juse use the same setDisplayHomeAsUpEnabled method you mentioned to begin with on the ActionBar after setting your toolbar as the ActionBar to get the back / up button.
sample to access it from fragment :
((AppCompatActivity)getActivity()).getSupportActionBar().setSubtitle();
Hope it helps.
As simple as this.
Toolbar toolbar = ((ChoosingActivity)getActivity()).findViewById(R.id.toolbar);
Now do whatever you want to do man ;).
It's probably because your Toolbar is covered by everything else in DrawerLayout. Try swapping LinearLayout and DrawerLayout, so that the vertical LinearLayout is your root layout, something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerChooser"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/new_gradients"
android:fitsSystemWindows="true"
tools:context=".ChoosingActivity">
<FrameLayout
android:id="#+id/fragment_container_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer_menu">
</android.support.design.widget.NavigationView>
</LinearLayout>
Something approximately like that, the key is that your Toolbar has to be outside your DrawerLayout.

Title not showing in Toolbar when part of DrawerLayout

I'm new to Android programming.
I'm trying to replicate an IOS app of mine while learning the ropes.
I'm not using Android Studio wizards to create any activities - doing everything manually so that I may understand what goes on.
I've setup an AppCompat activity using a DrawerLayout and a toolbar.
Initially, before I noticed the existence of DrawerLayout I had setup the same overall design using a RelativeLayout.
While my Toolbar was inside the Relative Layout, I could set its title without a problem.
When I replaced RelativeLayout and put the Toolbar inside the DrawerLayout the title stopped displaying.
I can see in the debugger that the title is getting set correctly, it just does not show up.
I have currently tied up an ActionBarDrawerToggle with DrawerLayout.
Previously, I was not using an ActionBarDrawerToggle.
In both cases, Toolbar title is not displaying.
If I restore RelativeLayout, the title is showing up again.
I have searched everywhere in SO but can't find a solution.
Layout for the activity is this:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/app_drawer">
<include layout="#layout/toolbar"/>
<FrameLayout
android:id="#+id/fragment_items_list_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:layout_marginTop="52dp"
/>
<LinearLayout
android:orientation="vertical"
android:layout_width="256dp"
android:layout_height="match_parent"
android:background="#color/lightGray"
android:id="#+id/fragment_nav_list_container"
android:layout_gravity="start"
/>
Layout for the toolbar is this:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_height="52dp"
android:layout_width="match_parent"
android:minHeight="52dp"
android:background="?attr/colorPrimary">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="App Title"
android:gravity="center"
android:textColor="#ffffff"
android:textSize="20dp"
android:textStyle="bold"
android:background="#color/red"
/>
Code for the activity is this:
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
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.util.Log;
import android.view.View;
import android.widget.TextView;
import DatabaseMaster;
public class MainWrapperActivity extends AppCompatActivity {
class MainWrapperDrawerToggle extends ActionBarDrawerToggle {
public MainWrapperDrawerToggle(Activity activity, DrawerLayout drawerLayout, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
super(activity, drawerLayout, openDrawerContentDescRes, closeDrawerContentDescRes);
}
public MainWrapperDrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
super(activity, drawerLayout, toolbar, openDrawerContentDescRes, closeDrawerContentDescRes);
}
// Drawer Listener
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView,slideOffset);
Log.d("debug","Main App Drawer: SLIDE");
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
Log.d("debug","Main App Drawer: OPENED");
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Log.d("debug","Main App Drawer: CLOSED");
}
#Override
public void onDrawerStateChanged(int newState) {
super.onDrawerStateChanged(newState);
Log.d("debug", "Main App Drawer: STATE CHANGED: " + newState);
}
}
private MainWrapperDrawerToggle mActionBarDrawerToggle;
private DrawerLayout mDrawerLayout;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_wrapper);
// Add / Configure Toolbar
mToolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
// Setup App Drawer
mDrawerLayout=(DrawerLayout)findViewById(R.id.app_drawer);
mActionBarDrawerToggle=new MainWrapperDrawerToggle(this,mDrawerLayout,mToolbar,R.string.app_name,R.string.app_name);
mDrawerLayout.addDrawerListener(mActionBarDrawerToggle);
//getSupportActionBar().setHomeButtonEnabled(true);
//getSupportActionBar().setDisplayShowTitleEnabled(false);
//mActionBarDrawerToggle.setHomeAsUpIndicator(R.drawable.ic_nav_menu);
// Add Fragment(s)
FragmentManager fm=getSupportFragmentManager();
// Check for existing fragment by the ID of its Container
Fragment fragment=fm.findFragmentById(R.id.fragment_items_list_container);
if (fragment == null) {
fragment=new SectionsListFragment();
// Add fragment to it's Container
fm.beginTransaction().add(R.id.fragment_items_list_container,fragment).commit();
}
}
#Override
protected void onPostCreate (Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mActionBarDrawerToggle.syncState();
mToolbar.setNavigationIcon(R.drawable.ic_nav_menu);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onStart () {
super.onStart();
}
#Override
protected void onResume () {
super.onResume();
TextView toolbarTitleView=(TextView)mToolbar.findViewById(R.id.toolbar_title);
toolbarTitleView.setText(R.string.app_name);
}
#Override
protected void onDestroy () {
DatabaseMaster.getInstance().getRealm().close();
DatabaseMaster.getInstance().setRealm(null);
super.onDestroy();
}
#Override
public boolean onSupportNavigateUp () {
Log.i("debug", "Toggling hamburger menu");
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
} else {
mDrawerLayout.openDrawer(GravityCompat.START);
}
return false;
}
}
DrawerLayout only contains two childs i.e. only two layouts. You can replace your FrameLayout with another RelativeLayout and place your FrameLayout and include tag in that new RelativeLayout.
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/app_drawer">
<include layout="#layout/new_container"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="256dp"
android:layout_height="match_parent"
android:background="#color/lightGray"
android:id="#+id/fragment_nav_list_container"
android:layout_gravity="start"/>
</android.support.v4.widget.DrawerLayout>
And in Relative Layout Use this
<RelativeLayout
android:id="#+id/new_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/toolbar"/>
<FrameLayout
android:id="#+id/fragment_items_list_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"/>
</RelativeLayout>
Rest is fine.Hope This Help.

Android drag margin for navigation drawer is off screen

I have recently created an app called Hoops and I have been developing it for quite some time now. However, the main problem that I seem to be getting, is that the navigation drawer's swipe margin is off screen and other users find it incredibly hard to use the navigation drawer's swipe feature. The menu button works just fine though. I have looked at other tutorials online and all of them seem to be showing the same answer as the one in the forum I have linked: Set drag margin for Android Navigation Drawer
However, I have tried this solution, and it does not seem to be working for me. If anyone has any ideas why it is not working please can you help me out. Here is the coding for the Main activity with the navigation drawer below:
package com.jehan.sportstutorials;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
Toolbar toolbar;
ActionBar actionBar;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
actionBar.setDisplayHomeAsUpEnabled(true);
drawerLayout = (DrawerLayout) findViewById(R.id.navigation_drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
if (navigationView != null) {
setupNavigationDrawerContent(navigationView);
}
setupNavigationDrawerContent(navigationView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupNavigationDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
textView = (TextView) findViewById(R.id.textView);
switch (menuItem.getItemId()) {
case R.id.item_navigation_drawer_basketball:
menuItem.setChecked(true);
textView.setText(menuItem.getTitle());
drawerLayout.closeDrawer(GravityCompat.START);
Intent i = new Intent(MainActivity.this, BasketballTutorial.class);
startActivity(i);
return true;
case R.id.item_navigation_drawer_help:
menuItem.setChecked(true);
textView.setText(menuItem.getTitle());
drawerLayout.closeDrawer(GravityCompat.START);
Intent intent2 = new Intent(MainActivity.this, HelpScreen.class);
startActivity(intent2);
return true;
}
return true;
}
});
}
}
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"
android:id="#+id/navigation_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="#bool/fitsSystemWindows">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="#dimen/status_bar_kitkat_height"
android:background="?colorPrimary"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="?colorPrimaryDark"/>
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/welcome"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textColor="#color/md_text"
android:singleLine="false"
android:padding="20dp"
android:gravity="center"
android:textStyle="bold"
android:textIsSelectable="false" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|bottom"
android:text="#string/swipe"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textColor="#color/md_text"
android:singleLine="false"
android:padding="20dp"
android:gravity="center"
android:textSize="20sp"
android:textStyle="italic"
android:layout_marginBottom="30dp"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="25dp"
android:background="?colorPrimaryDark"/>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:minHeight="?attr/actionBarSize"
android:background="#drawable/action_bar_color"
android:elevation="4dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ToolbarTheme"
android:layout_marginTop="25dp"/>
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="#bool/fitsSystemWindows"
app:headerLayout="#layout/navigation_drawer_header"
app:menu="#menu/navigation_drawer_menu"
app:theme="#style/NavigationViewTheme" />
If anyone wants a live example of the navigation drawers swipe feature not working you can test out my app in the app store. Here is the link: https://play.google.com/store/apps/details?id=com.jehan.sportstutorials
Summary: Does anyone know how to increase the navigation drawers drag margin, however not following the conventional methods stated in the link in my first paragraph? Help would be appreciated.
Check your R.layout.activity_main layout. Android Studio IDE, for some reason, sets 15dp margin to the topmost container of automatically-created Activity layouts. This could interfere with the Drawer.
Just check if the topmost Relative/Frame/Whichever Layout has any android:layout_marginX attributes set and remove them.

Categories

Resources