Add back navigation to an appBarLayout, I want to add a toolbar inside an appBarLayout in xml, and then add a back arrow to that toolbar.
I have followed this and tried to adjust it for my needs, with no luck.
Display Back Arrow on Toolbar
According to Android Docs
AppBarLayout is a vertical LinearLayout
So you will need to include your toolbar and other components inside it, something like:
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<android.support.v7.widget.Toolbar
...
app:layout_scrollFlags="scroll|enterAlways"/>
<android.support.design.widget.TabLayout
...
app:layout_scrollFlags="scroll|enterAlways"/>
</android.support.design.widget.AppBarLayout>
Then you can add your back navigation button to the toolbar:
Toolbar toolbar = (Toolbar) findViewById(R.id.Your_Toolbar);
setSupportActionBar(toolbar);
And then calls to:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Override method:
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
In your activity do the following in onCreate
ActionBar bar = getSupportActionBar();
if(bar != null){
bar.setDisplayHomeAsUpEnabled(true);
}
Related
I want to add a Back button in a toolbar that I created because I deleted the default one to have the material design effect with some tabs, but every time I add the code to make that button appear, Android gives an exception saying this:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.juan.sdfnsdfnskdfnskdfmsfd, PID: 13348
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.support.v4.widget.DrawerLayout.getDrawerLockMode(int)' on a null object reference
at android.support.v7.app.ActionBarDrawerToggle.toggle(ActionBarDrawerToggle.java:284)
at android.support.v7.app.ActionBarDrawerToggle$1.onClick(ActionBarDrawerToggle.java:202)
at android.view.View.performClick(View.java:6308)
at android.view.View$PerformClick.run(View.java:23969)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1557)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
I do not understand what it means with a null object reference if I only write the corresponding code in the toolbar that I created.
This is the 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:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/toolbar_morado"
android:id="#+id/toolbar_lista_compras"
android:minHeight="?attr/actionBarSize">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/contador_toolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lista de compras"
android:textSize="18sp"
android:textColor="#ffffff"/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
This is where I implement the 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"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:id="#+id/appBarLayoutCalcular">
<include layout="#layout/toolbar"></include>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tablayoutCalcular"
app:tabGravity="fill"
app:tabMode="fixed"
android:background="#color/toolbar_anaranjado"
app:tabTextAppearance="#style/myTabSize"
app:tabIndicatorColor="#5c1be1"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewPagerCalcular"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
This is my class:
public class CalculateMaterials extends AppCompatActivity{
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
Toolbar toolbar;
NavigationView navigationView;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
String tabSeleccionado;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calcular_materiales);
toolbar = (Toolbar)findViewById(R.id.toolbar_shopping_list);
toolbar.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.toolbar_anaranjado));
setSupportActionBar(toolbar);
// text for the toolbar
TextView textoToolbar = (TextView)findViewById(R.id.contador_toolbar);
textoToolbar.setText("Calcular los materiales");
// status bar color
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(getApplicationContext(), R.color.statusBar_anaranjado));
}
// adding toolbar back button
// this is where I have the error
if (toolbar != null) {
toolbar.setNavigationIcon(R.drawable.backButton);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
navigationView = (NavigationView)findViewById(R.id.navigationView);
tabLayout = (TabLayout)findViewById(R.id.tablayoutCalcular);
viewPager = (ViewPager)findViewById(R.id.viewPagerCalcular);
// adding the tabs
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new FragmentCalcular(), "Con area");
viewPagerAdapter.addFragments(new FragmentCalcular2(), "Con metros");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
I also try with:
// add back arrow to toolbar
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
That also gives the same error.
So, Can anyone help me with this problem?
Edit
Thanks to everyone who tried to help me with this problem. I finally found the error.
Some time ago, I tried to add a navigationView in all the activities, but I forgot to delete the necessary code in the class, that's why the drawerLayout doesnt appears in the xml.
So, when I delete the drawerLayout variable, everything works!
Try this
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
Try this.
toolbar = (Toolbar) findViewById(R.id.toolbar_editprofile);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false):
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back_arrow));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
It seems like drawerLayout is null. I can't able to find find your "drawer_layout" in XML.
Make sure you are using the same id for the navigation drawer in findViewById(R.id.drawer_layout) and in the layout file.
First thing where is your DrawerLayout ? i cant find it from your question may be you forgot to post it or not created yet.
make sure you have to declare correct ID for DrawerLayout so check drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout); of drawer_layout.xml
Error Line: i have found error in this line may be this is not your answer but should have to correct you
TextView textoToolbar = (TextView)findViewById(R.id.contador_toolbar);
Try This
toolbar = (Toolbar)findViewById(R.id.toolbar_shopping_list);
toolbar.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.toolbar_anaranjado));
setSupportActionBar(toolbar);
// text for the toolbar
TextView textoToolbar = (TextView)toolbar.findViewById(R.id.contador_toolbar);
textoToolbar.setText("Calcular los materiales");
In onCreate method paste this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolBarGig);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
after this you have to override method:-
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
Try this. Hope it will helps you!
First initialize the toolbar bar for back button
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
then call back button method this code is enough to go to previous
activity else you can use intent method inside onBackPressed method to
go back
//method on back button click
#Override
public void onBackPressed() {
super.onBackPressed();
/*OR
Intent forgot_password = new Intent( AddItemActivity.this, HomeActivity.class);
startActivity(forgot_password);
finish();
}*/
back button click functionality
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
EDIT: For those like me who just want an image locked in the upper left-hand corner of their screen, you can set a logo to replace the app launcher icon in the corner and that accomplished this easily.
I want to have an image in the upper left-hand corner of my screen in the ActionBar instead of the icon and name of the app. So far I have gotten it there but it moves and changes size depending on what other icons are in the action bar (I have icons appear and disappear). It is also centered on the remaining space and not simply in the center.
Is there a way I can lock this image to the lefthand corner? This is how fit it into the ActionBar below.
public void ActionBarCreation(){
getActionBar().setDisplayShowHomeEnabled(false);
getActionBar().setDisplayShowTitleEnabled(false);
ImageView img = new ImageView(getApplicationContext());
img.setImageResource(R.drawable.my_image);
// 7 padded on the bottoms so it does not cover the dividing line.
img.setPadding(0, 0, 0, 7);
getActionBar().setCustomView(img);
getActionBar().setDisplayShowCustomEnabled(true);
}
Put your theme for application as
<android:theme="#android:style/Theme.NoTitleBar">
-> this will get rid off your default toolbar with app name.
Next add your own toolbar layout in your activity layout
<android.support.v7.widget.Toolbar
android:id="#+id/my_awesome_toolbar"
android:layout_height="256dp"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_horizontal"
android:id="#+id/image"
//your drawable and customizations here
android:background="#android/color/transparent"
/>
</android.support.v7.widget.Toolbar>
Now set this toolbar as your activity's toolbar:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
}}
Im new to android development and am really struggling to implement a more custom toolbar (or action bar) when using the navigation drawer created in android studio. When I created the navigation drawer activity from the template, the file that seems to be defining the tool bar is app_bar_main.xml
here is app_bar_main.xml
<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="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
android:title="Press"
android:titleTextColor="#FFFFFF"
/>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
As you can see, I have tried to change the title (to press) and text color of the tool bar, however when running it, nothing changes and it still just says MainActivity which is what my Navigation drawer activity is called. How can I define this toolbar so I can customize it (center the title, make the background transparent, remove settings button, etc. I do need to keep the hamburger icon to open the drawer obviously)
Thanks for the future help everyone! Let me know if I need to provide any other pieces of my code
Setting the values inside of xml for the toolbar has never worked for me either. You should do them pragmatically. If you are generating the code from Android Studio, you will see inside of onCreate that it is setting the toolbar to the ActionBar:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
One possible option is to remove setSupportActionbar().
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
toolbar.setTitle("Testing");
toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.colorAccent));
toolbar.inflateMenu(R.menu.menu_main);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
});
}
The other is to call getSupprtActionBar()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.colorAccent));
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("Testing");
}
}
/**
* Here is where you would handle the actionbar items.
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
I tried to change the colour of my action bar in Android app using the following line of code:
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.background_actionbar)));
However, this gives a warning that reads:
Method invocation 'getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.backgr...' may produce 'java.lang.NullPointerException'
Any ideas how to work around this?
Note: I am changing the colour programmatically because changing it via XML theme/style didn't work.
Using minimum SDK 16.
Testing on Android 4.4.4 device.
Yes, If you are using themes with NoActionBar then you will get the NullPointerException.
Try this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The Action Bar is a window feature. The feature must be requested
// before setting a content view. Normally this is set automatically
// by your Activity's theme in your manifest. The provided system
// theme Theme.WithActionBar enables this for you. Use it as you would
// use Theme.NoTitleBar. You can add an Action Bar to your own themes
// by adding the element <item name="android:windowActionBar">true</item>
// to your style definition.
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.main);
// experiment with the ActionBar
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.background_actionbar)));
//actionBar.hide();
}
or
You can use Toolbar
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<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/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:minHeight="?attr/actionBarSize"
android:background="#color/light_blue">
</android.support.v7.widget.Toolbar>
Include it in activity's layout:
<?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">
<LinearLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include layout="#layout/toolbar" />
</LinearLayout>
</RelativeLayout>
Use this code to Activity:
public class YourActivity extends AppCompatActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//toolbar.setTitle("Setting");
}
public void setSupportActionBar(#Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
}
I want something like this: link . A little arrow and icon but in a toolbar.
EDIT:
I have tried this:
mToolbar = (CustomToolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mToolbar.setNavigationIcon(R.drawable.ic_ab_back_holo_light);
mToolbar.setTitle(mMatchName);
mToolbar.setLogo(R.mipmap.ic_options);
getSupportActionBar().setHomeButtonEnabled(true);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
overridePendingTransition(0, R.anim.slide_right);
}
});
But this makes a big distance between arrow icon and Logo.
Question:
How do I put an arrow and a logo next to each other?
Your link takes you to an example of the old ActionBar, but you seem to be using the new toolbar. The new toolbar design doesn't have icons like the old version, only text, so the extra space is by design. If you want to use something like you linked then you need to use the ActionBar not a toolbar.
Here is a link on the new toolbar:
https://blog.xamarin.com/android-tips-hello-toolbar-goodbye-action-bar/
vs. the old ActionBar
https://developer.android.com/training/basics/actionbar/index.html
After some experiments I've found how to achieve in a toolbar the Up Navigation like this one:
We can create a custom layout and put it in a toolbar.
1) in onCreate method:
mToolbar = (CustomToolbar) findViewById(R.id.toolbar);
setUpCustomUpNavigation();
setSupportActionBar(mToolbar);
// to disable title in a toolbar
getSupportActionBar().setDisplayShowTitleEnabled(false);
2) setUpCustomUpNavigation() method.
private void setUpCustomUpNavigation() {
LayoutInflater mLayoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View customUpNavView = mLayoutInflater.inflate(R.layout.up_navigation_layout, null);
// "ic_ab_back_holo_light.png" Located in ...android-sdk\platforms\android-14\data\res\drawable-xhdpi
ImageView backArrowImageView = (ImageView) customUpNavView.findViewById(R.id.backArrowImageView);
ImageView logoToolbarImageView = (ImageView) customUpNavView.findViewById(R.id.logoToolbarImageView);
TextView titleTextView = (TextView) customUpNavView.findViewById(R.id.titleTextView);
// set logo
logoToolbarImageView.setImageResource(R.drawable.help_toolbar_ic_selector);
// set title
titleTextView.setText(R.string.title_activity_help);
mToolbar.addView(customUpNavView);
}
3) toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<net.stargorod.dating.toolbar.CustomToolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:background="#color/colorPrimary"
android:minHeight="?actionBarSize"
style="#style/MyToolbar" />
4) in style.xml create the style: MyToolbar.
<!-- Toolbar style -->
<style name="MyToolbar" parent="Widget.AppCompat.ActionBar">
<item name="contentInsetStart">0dp</item>
<item name="contentInsetEnd">0dp</item>
<item name="android:padding">0dp</item>
</style>
Result:
That's it!
P.S. I'm sorry for my grammar mistakes.