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