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.
Related
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
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.
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.
I had Created a Home activity which includes Tablayout and Navigation Drawer onclick with fragment. I had included fragmentTransaction.addToBackStack(null).commit(); with the fragment transaction code to go back to previous Activity.
My Desired requirement was From Activity with tablayout-->NavigationDrawer-->Fragment1--> On BackButtonPress-->MainActivity with tablayout.
But,Now i am able to move to Fragment1,and when return to MainActivity,the view becomes filled with white(if i use mainLayout.removeAllViews(); and if wont use mainLayout.removeAllViews(); ,then the fragment is overlapping with the MainActivity)
1.My mainactivty
2.fragment
3.when i return to mainactivty
Now i cant see tablayout in my MainActivity.
Can anyone please help me.
mainactivity_layout.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:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".HomeActivity"
android:id="#+id/mainlayout"
tools:showIn="#layout/app_bar_home">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel">
<RelativeLayout
android:id="#+id/main_layout1"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout1"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
MainActivity.java
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import java.io.File;
import java.util.ArrayList;
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#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);
TabLayout tabLayout1 = (TabLayout) findViewById(R.id.tab_layout1);
tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_home));
tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_map));
tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_login));
tabLayout1.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager1 = (ViewPager) findViewById(R.id.pager1);
final PagerAdapter1 adapter = new PagerAdapter1
(getSupportFragmentManager(), tabLayout1.getTabCount());
viewPager1.setAdapter(adapter);
viewPager1.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout1));
tabLayout1.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager1.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
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) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Handle navigation view item clicks here.
int id = item.getItemId();
RelativeLayout mainLayout=(RelativeLayout)findViewById(R.id.main_content);
if (id == R.id.nav_login) {
LoginFragment fragment = new LoginFragment();
// mainLayout.removeAllViews();
fragmentTransaction.replace(R.id.mainlayout, fragment);
fragmentTransaction.addToBackStack(null).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Fragment.java
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
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 com.google.android.gms.maps.model.MarkerOptions;
public class ContactFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
Button call;
public ContactFragment() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_contact,container,false);
call = (Button) v.findViewById(R.id.button5);
call.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_DIAL);
i.setData(Uri.parse("tel:7034409615"));
startActivity(i);
}
});
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(9.2700, 76.7800);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Pathanamthitta"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
As I suggested in the comments, in order to figure out the problem with displaying of fragments you can try to view what kind of fragments are being added into back stack as follows
Log.d("FragmentList",getSupportFragmentManager().getFragments().toString();
You can put it inside onBackPressed() ,onNavigationItemSelected()
According to your feedback it was helpful for you and you figured out the problem.
Also there are some layout design issues:
Your current approach is to adding fragment into relative layout. I believe it leads to some problems with view. The recommended approach is to add fragments into FrameLayout as described in docs
Also you may want to move everything outside view used for fragments
I have rewritten your layout following recommended guidelines in the docs. P.S I haven't tested how it displayed.. you may have to tweak some layout params.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--
Layout for fragments
-->
<FrameLayout
android:id="#+id/mainlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_home">
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel">
<RelativeLayout
android:id="#+id/main_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" android:orientation="horizontal"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout1"/>
</RelativeLayout>
</RelativeLayout>
</LinearLayout>
Also You defined multiple activities in your layout like tools:context=".MainActivity" and tools:context=".HomeActivity" I guess it's just unedited copy paste, but may lead some issues as well.
Hope you find it useful :)
In your MainActivity.java add this:
protected OnBackPressedListener onBackPressedListener;
public interface OnBackPressedListener {
void doBack();
}
public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
this.onBackPressedListener = onBackPressedListener;
}
#Override
public void onBackPressed() {
if (onBackPressedListener != null)
onBackPressedListener.doBack();
else
super.onBackPressed();
}
Than in Fragment.java implements class like this:
implements MainActivity.OnBackPressedListener
And implements method:
#Override
public void doBack() {
Intent yourMainActivity = new Intent(getActivity(), MainActivity.class);
startActivity(yourMainActivity);
}
Rubin Nellikunnathu. I had the same issue. Make replacing of your NavigationView fragments in FrameLayout, not RelativeLayout. So you always would have TabLayout and ViewPager loaded.
Place it in mainactivity_layout.xml or in app_bar_home.xml (I do not see your full code, so you try these combinations).
mainactivity_layout.xml
<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:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".HomeActivity"
android:id="#+id/mainlayout"
tools:showIn="#layout/app_bar_home">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel">
<RelativeLayout
android:id="#+id/main_layout1"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout1"/>
</RelativeLayout>
</RelativeLayout>
// Replace NavigationView fragments in this FrameLayout
<FrameLayout
android:id="#+id/flForReplace"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FrameLayout" />
</RelativeLayout>
and your code should be
fragmentTransaction.replace(R.id.flForReplace, fragment);
also replace fragmentTransaction.addToBackStack(null).commit(); with fragmentTransaction.commit(); as ρяσѕρєя K suggested.
I have been working on a navigation drawer using toolbar and while clicking on the drawer items , respective fragments will be displayed,but here is the problem,when ever I am clicking the drawer items ,fragments with two toolbars are displayed.please help.
fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="archerpenny.impdrawerfragment.BlankFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<!-- TODO: Update blank fragment layout -->
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</LinearLayout>
</FrameLayout>
My Activity_main.xml..
`<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/Container"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="hi"/>
</FrameLayout>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/DrawerList"
android:layout_marginTop="?android:attr/actionBarSize"
android:background="#mipmap/menu_bg"
android:layout_gravity="left"/>
</android.support.v4.widget.DrawerLayout>
MainActivity.java....
`
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
public class MainActivity extends AppCompatActivity {
ActionBarDrawerToggle mDrawerToggle;
RecyclerView.Adapter mAdapter;
RecyclerView recyclerView;
DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new NavigationDrawerAdapter(this);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationDrawerAdapter adapter;
recyclerView = (RecyclerView)findViewById(R.id.DrawerList);
recyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
recyclerView.setLayoutManager(llm);
recyclerView.setAdapter(mAdapter);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout,toolbar,R.string.open,R.string.close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(MainActivity.this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// do whatever
if(position==0)
{
BlankFragment blankFragment=new BlankFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.Container, blankFragment)
.commit();
}
mDrawerLayout.closeDrawers();
}
})
);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
BlankFragment.java
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class BlankFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
return fragment;
}
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
AppCompatActivity activity = (AppCompatActivity) getActivity();
View view=inflater.inflate(R.layout.fragment_blank, container, false);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
activity.setSupportActionBar(toolbar);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Inflate the layout for this fragment
return view;
}
}
Remove the include statement in your fragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="archerpenny.impdrawerfragment.BlankFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- TODO: Update blank fragment layout -->
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</LinearLayout>
For those who came here from search for two Toolbars in a fragment.
There is a similar topic: Double Toolbar Is Showing on Fragment.
In AndroidManifest set a theme:
<activity
android:name=".YourActivity"
android:label="#string/title"
android:theme="#style/AppTheme.NoActionBar" />
The theme is:
<style name="AppTheme.NoActionBar" parent="AppTheme">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
</style>
In YourActivity extend it from AppCompatActivity and add ActionBar, so write:
class YourActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fragment)
setToolbar(toolbar)
showFragment()
// Handle onResume() in fragments, if needed.
supportFragmentManager.addOnBackStackChangedListener {
supportFragmentManager.fragments.lastOrNull()?.onResume()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// 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.
return when (item.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
fun setToolbar(toolbar: Toolbar) {
setSupportActionBar(toolbar)
// Show back arrow.
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
// Additional settings, if needed.
toolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.white))
val toolbarTextColor = ContextCompat.getColor(this, R.color.blue)
toolbar.setTitleTextColor(toolbarTextColor)
toolbar.navigationIcon?.setColorFilter(toolbarTextColor, PorterDuff.Mode.SRC_ATOP)
toolbar.overflowIcon?.setColorFilter(toolbarTextColor, PorterDuff.Mode.SRC_ATOP)
}
private fun showFragment() {
if (supportFragmentManager.findFragmentByTag(YourFragment.TAG) == null) {
val fragment = YourFragment.newInstance()
supportFragmentManager.beginTransaction()
.replace(R.id.container, fragment, YourFragment.TAG)
.commit()
}
}
}
This is a layout for YourActivity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
app:popupTheme="#style/AppTheme.PopupOverlay"
/>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
</android.support.design.widget.CoordinatorLayout>
Previous attempts (do not repeat).
I made many experiments. Created a new project. Copied all suspecting activities and fragments, styles, colors, strings, dimens, changed AndroidManifest. Set a theme of the activity not from ...NoActionBar style. Removed Toolbar with surrounding <android.support.design.widget.AppBarLayout> tag in activity layout. In onCreate() wrote:
// setSupportActionBar(toolbar) // Crashing string.
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
Then I copied the project to another folder and after compilation it showed one Toolbar. Even if in the source folder I launched File > Invalidate caches and Restart, nothing happened. So, after invalidating caches, Build > Rebuild Project (probably Build > Clean Project) it showed one Toolbar. I even returned back AppBarLayout. I blamed Android Studio.
But on the next day this magic stopped to execute. I compiled the same project and again got two Toolbars. And copying folders, invalidating, deleting /build folders didn't help. So I began to research repository commits in order to catch a solution. It is written in the beginning of the answer.