fragment to activity Backstack returns blank view - android

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.

Related

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.

How to force the buttons in bottom navigation to be at the bottom in android studio

I am trying to use bottom navigation but the buttons or icons appears in the middle not in the bottom, I have use drawer navigation in the same activity i.e. I declare a drawer layout in the xml resource layout.
?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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello"/>
</LinearLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="168dp"
android:layout_height="168dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
<android.support.design.widget.NavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:menu="#menu/drawer"
android:layout_gravity="start">
</android.support.design.widget.NavigationView>
The code of this activity:
package com.example.welcome.madrasti;
import android.content.ClipData;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
Intent intent1;
private DrawerLayout d;
private ActionBarDrawerToggle a;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_dashboard:
return true;
case R.id.navigation_home:
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
d = (DrawerLayout) findViewById(R.id.container);
a= new ActionBarDrawerToggle(MainActivity.this,d,R.string.open,R.string.close);
d.addDrawerListener(a);
a.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
intent1= new Intent(getApplicationContext(),MapsActivity.class);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(a.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
}
Is there any idea ?. I have got the bottom navigation as follows : here
Changing padding at the Bottom to small a value like:
android:paddingBottom="2dp"
Also your BottomNavigationView appears to be a square of 168dp size. Is this intentionally? Change the height it or view its layout bounds. It may be very big by itself like a square.

Adding Tablayout and Toolbar to the Top of the screen

I want to create DetailActivity for My app . I want To achieve layout some thing like This .
Look at to the green rectangle .it is contain Toolbar and Tablayout .
When we scroll down and when toolbar Touch the Tablayout . They pinned to the top of the screen.
I Think this Layout use the Scroll and ... and use The Toolbar and Tablayout in The Activity .
This is my code where I try to achieve That.but nothing ...
DeatailActivity.java
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import ir.dink.sevom.R;
import ir.dink.sevom.adapters.*;
public class DetailActivity extends AppCompatActivity {
private ViewPager detailActivityViewPager;
private TabLayout detailActivityTabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
initToolbar();
initTablayout();
}
//============================ Init Toolbar ===================================//
private void initToolbar() {
Toolbar mainToolbar = (Toolbar)findViewById(R.id.toolbar_detail_activity);
setSupportActionBar(mainToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
//========================== OnCreate Option Menu =====================================//
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//=============================== onOption Item Selected ================================//
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.search_action_toolbar:
// startActivity(new Intent(MainActivity.this ,DetailActivity.class ));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void initTablayout() {
detailActivityViewPager = (ViewPager) findViewById(R.id.view_pager_detail_activity);
detailActivityTabLayout = (TabLayout) findViewById(R.id.tab_layout_detail_activity);
FragmentManager manager = getSupportFragmentManager();
DetailActivityPagerAdapter detailadapter = new DetailActivityPagerAdapter(manager);
detailActivityViewPager.setAdapter(detailadapter);
detailActivityViewPager.setCurrentItem(detailActivityViewPager.getAdapter().getCount() - 1);
detailActivityTabLayout.setupWithViewPager(detailActivityViewPager);
detailActivityViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(detailActivityTabLayout));
}
}
And This is The Xml of That :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ir.dink.sevom.activities.DetailActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_detail_activity"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#android:color/transparent"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<ImageView
android:id="#+id/img_detail"
android:layout_width="96dp"
android:layout_height="124dp"
android:layout_below="#id/toolbar_detail_activity"
android:src="#drawable/ic_hamburger"
android:layout_alignParentRight="true"
android:layout_margin="8dp"/>
<TextView
android:id="#+id/txt_name_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:text="نام :"
android:layout_toLeftOf="#+id/img_detail"
android:layout_alignTop="#+id/img_detail"/>
<TextView
android:id="#+id/txt_count_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:text="تعداد"
android:layout_toLeftOf="#+id/img_detail"
android:layout_below="#+id/txt_name_detail"
android:layout_marginTop="8dp"/>
<TextView
android:id="#+id/txt_last_update_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:text="آخرین آپدیت"
android:layout_toLeftOf="#+id/img_detail"
android:layout_below="#+id/txt_count_detail"
android:layout_marginTop="8dp"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout_detail_activity"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#4d4d4d"
android:layout_below="#id/img_detail"
app:tabMode="scrollable"
/>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager_detail_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/tab_layout_detail_activity"/>
</RelativeLayout>

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.

Two toolbars are visible in my fragment

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.

Categories

Resources