I am in the process of writing an android version of a iOS app I have helped create.
I am using a template navigation menu which puts a bar at the top and a menu at the side when dragged out or a button is pressed. This works fine, however the fragment comes with margins which leaves blank spaces between the bar and the layout.
I have tried removing the margins, but they then prevent the menu at the top from showing.
I am not sure which code snipped to include, so I have included the home.xml (fragment) activity_main.xml and the java files associated.
home.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_marginTop="70dp"
android:layout_marginLeft="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/tvNo"
android:layout_gravity="left" />
</LinearLayout>
activity_main.xml
<!-- The main content view -->
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- The ActionBar -->
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</include>
</FrameLayout>
<!-- The navigation drawer -->
<ListView android:id="#+id/lvDrawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:paddingTop="24dp"
android:divider="#android:color/darker_gray"
android:dividerHeight="0dp"
android:background="#android:color/background_light" />
</uk.co.mrgyro.cropcirclelocatorandroid.FragmentNavigationDrawer>
Home.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import uk.co.mrgyro.cropcirclelocatorandroid.R;
public class Home extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.home, container, false);
return rootView;
}
}
MainActivity.java
package uk.co.mrgyro.cropcirclelocatorandroid;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
private FragmentNavigationDrawer dlDrawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a ToolBar to replace the ActionBar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find our drawer view
dlDrawer = (FragmentNavigationDrawer) findViewById(R.id.drawer_layout);
// Setup drawer view
dlDrawer.setupDrawerConfiguration((ListView) findViewById(R.id.lvDrawer), toolbar,
R.layout.drawer_nav_item, R.id.flContent);
// Add nav items
dlDrawer.addNavItem("First", R.drawable.ic_one, "First Fragment", Home.class);
dlDrawer.addNavItem("Second", R.drawable.ic_two, "Second Fragment", SecondFragment.class);
dlDrawer.addNavItem("Third", R.drawable.ic_three, "Third Fragment", ThirdFragment.class);
// Select default
if (savedInstanceState == null) {
dlDrawer.selectDrawerItem(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
if (dlDrawer.isDrawerOpen()) {
// Uncomment to hide menu items
// menu.findItem(R.id.mi_test).setVisible(false);
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Uncomment to inflate menu items to Action Bar
// inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (dlDrawer.getDrawerToggle().onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
dlDrawer.getDrawerToggle().syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
dlDrawer.getDrawerToggle().onConfigurationChanged(newConfig);
}
}
This is how it looks with the margins added
This is how it looks with both margins in home.xml set to 0
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
</style>
</resources>
The appearance I would like is like the first image, except with no blank space.
Thank you in advance
I dont understand very well your activities design and your layouts. If you need a navigation drawer and an action bar, I would just create one activity which extends ActionBarActivityand the navigation drawer written in the main xml. then in the content side of the navigation drawer place your activity content. In the code retrieve the action bar and the drawer and customize them as you want. You wont probably have those issues with margins etc and would be much more clean.
Remove
android:layout_marginTop="70dp"
android:layout_marginLeft="20dp"
from your Home layout, and
android:fitsSystemWindows="true"
from your activity layout.
Related
I am trying to use the android navigation drawer with the action bar of AppCompatActivity. But when I implement the action bar the icon to open the navigation drawer is missing in it.
This is what I want to be displayed
This is a screenshot of my current action bar
You can see my code below.
This is my 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/main_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar displayed at the top -->
<include
layout="#layout/action_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer that comes from the left -->
<!-- Note that `android:layout_gravity` needs to be set to 'start' -->
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"/>
<!--app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_view" />-->
</android.support.v4.widget.DrawerLayout>
This is my action_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
</android.support.v7.widget.Toolbar>
This is my MainActivity
package com.blog.waiyanhein.llks.llks;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#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) {
// 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);
}
}
Why is the icon to open the navigation drawer missing using my code?
You didn't implement the NavigationDrawer in your Activityi guess.i've had the same problem and that fixed with the following code.
In your Activity:
private DrawerLayout drawerLayout;
In your onCreate:
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
drawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.home:
drawerLayout.closeDrawers();
return true;
default:
return true;
}
}
});
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle =
new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
Strings.xml:
<string name="openDrawer">Navigation</string>
<string name="closeDrawer">Close Navigation</string>
Then it should work.
Try this code,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
You may need to include:
actionBarDrawerToggle.syncState();
The answer here may help:
Appcompatv7 - v21 Navigation drawer not showing hamburger icon
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.
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.
Here is a screenshot of Google Maps Toolbar.
As you can see icons are aligned to the left instead of right (default behavior). I've tried adding android:layout_gravity="left" and android:gravity="left" to the toolbar but it didn't work. I also tried adding an internal LinearLayout (with same gravity values) to the Toolbar but that didn't work either. Any ideas?
I want to be able to use a regular Android menu with the Toolbar widget instead of recreating everything from scratch.
After some struggling and digging in Android Toolbar code I managed to make it work. Basically, the idea is to add a new android.support.v7.widget.ActionMenuView as child of the Toolbar, set its gravity to top|start, and then add the menu to that action menu view in your Activity. Here is the code:
my_toolbar.xml
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/tToolbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
android:background="?attr/colorPrimary"
android:gravity="center_vertical|start"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<android.support.v7.widget.ActionMenuView
android:id="#+id/amvMenu"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"/>
</android.support.v7.widget.Toolbar>
my_activity.xml
<RelativeLayout 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">
<!--Toolbar-->
<include
android:id="#+id/tToolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
layout="#layout/my_toolbar" />
</RelativeLayout>
MyActivity.java
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public final class MyActivity extends ActionBarActivity {
private ActionMenuView amvMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this layout includes the custom toolbar my_toolbar.xml
setContentView(R.layout.my_activity);
Toolbar t = (Toolbar) findViewById(R.id.tToolbar);
amvMenu = (ActionMenuView) t.findViewById(R.id.amvMenu);
amvMenu.setOnMenuItemClickListener(new ActionMenuView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
return onOptionsItemSelected(menuItem);
}
});
setSupportActionBar(t);
getSupportActionBar().setTitle(null);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// use amvMenu here
inflater.inflate(R.menu.my_activity_menu, amvMenu.getMenu());
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Do your actions here
return true;
}
}
If there is no special reason to add toolbar items as menu actions, UI controls can be directly added to the toolbar, and aligned similar to aligning any other item inside a layout.
For an example, following toolbar has a left aligned Spinner and a right aligned EditText.
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_actionbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/tab_background"
android:gravity="center_vertical">
<Spinner
android:id="#+id/categorySpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:hint="Name" />
</android.support.v7.widget.Toolbar>
I am getting an issue at trying to hide the action bar while scrolling down.Then while scrolling up,the action bar have to shown again.
For Eg:
I referred this Tutorial.Here you can see the output and respective codes related to hide and show the action bar.
I am showing the output what I get it till now.
After scrolling down:
The screenshot above shown, it hide the action bar tab also.But it have to hide only the action bar.That's the major issue.
After scrolling up:
The screenshot above shows it displays back the action bar with tabs.
TopRatedFragment.java:
import info.androidhive.tabsswipe.R;
import android.app.ActionBar;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.widget.ScrollView;
public class TopRatedFragment extends Fragment implements ViewTreeObserver.OnScrollChangedListener {
private float mActionBarHeight;
private ActionBar actionBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
final TypedArray styledAttributes = getActivity().getTheme().obtainStyledAttributes(
new int[] { android.R.attr.actionBarSize });
mActionBarHeight = styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
actionBar = getActivity().getActionBar();
((ScrollView)rootView.findViewById(R.id.parent)).getViewTreeObserver().addOnScrollChangedListener(this);
return rootView;
}
#Override
public void onScrollChanged() {
float y = ((ScrollView)getActivity().findViewById(R.id.parent)).getScrollY();
if (y >= mActionBarHeight && actionBar.isShowing()) {
actionBar.hide();
} else if ( y==0 && !actionBar.isShowing()) {
actionBar.show();
}
}
}
fragment_top_rated.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="?android:attr/actionBarSize"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<Button
android:id="#+id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
.
.
</LinearLayout>
</ScrollView>
My issue is, While scrolling down it only have to hide the action bar only not action bar tabs.
I think this library and its sample could help you.
Look at the top-right gif animation:
I think the sample file is called "ViewPagerTabScrollViewActivity"