Custom toolbar on android navigation drawer - java

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;
}

Related

How to add a back navigation icon to an appBarLayout in java

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);
}

App crashes when trying to call SetSupportActionBar

I have made an app that works fine and uses a default toolbar. However I want to add navigation buttons to this toolbar so I am implementing my own that I can inflate a menu onto it. However when I try to call SetSupportActionBar() the app crashes.
I have tried to set the app to not use the default action bar in both the manifest: <activity android:name=".MainMenu" android:theme="#style/Theme.AppCompat.NoActionBar"/> as well as in the XML file: android:theme="#style/Theme.AppCompat.NoActionBar", as this was the suggested solution for someone else with a similar issue however this has not worked.
The code I am using is as follows;
XML:
<Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Java:
public class MainMenu extends AppCompatActivity {
Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
mToolbar = findViewById(R.id.my_toolbar);
setSupportActionBar(mToolbar);
mToolbar.setNavigationIcon(R.drawable.menu_arrow);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
Change the toolbar's xml to:
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
instead of Toolbar
also look at your imports, if you have this line:
import android.widget.Toolbar;
replace it with:
import android.support.v7.widget.Toolbar;

toolbar back button error Android

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);
}
}

Changing Action Bar Colour Programmatically may cause nullPointerException?

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);
}
}

android toolbar inside a tab

I want to make a toolbar inside one of my tabs but nothing works for me. Can this even be done? I currently have a toolbar above my tabs but i need it to appear inside the first tab.
Here's the code (with the toolbar above tabs):
import ...
public class MainActivity extends ActionBarActivity {
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[] = {"Projects", "People", "Files"};
int Numboftabs = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setViewPager(pager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_primary, menu);
return true;
}
final ArrayList<String> listItems = new ArrayList<String>();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.addButton) {
final TextView noProject = (TextView) findViewById(R.id.NOPROJECT);
final ListAdapter addAdapter = new ArrayAdapter<String>(this,
R.layout.list_item, R.id.listFrame, listItems);
final ListView lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(addAdapter);
noProject.setVisibility(View.GONE);
lv.setVisibility(View.VISIBLE);
listItems.add("New Project");
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent switchToEdit = new Intent(MainActivity.this,
TeamCreate.class);
startActivity(switchToEdit);
}
});
}
return super.onOptionsItemSelected(item);
}
}
First tab:
import ...
public class Tab1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
return v;
}
}
I faced a similar challenge with a non-standard toolbar and tabs and got past it, though frankly the results were odd looking. You can probably get the toolbar to work under the tab using a similar technique, however it may leave your users scratching their heads. Your technique will have 2 toolbars, one holding the TabLayout widget and another one inside the fragment(s) in the ViewPager.
I was using Material Design tabs for the Detail view in my app. It looked fine until I did the 2-pane Master-Detail view for tablets. Then I had an issue with the tabs wanting to be directly under the toolbar, but no obvious way to have the Master & Detail share the toolbar with the tabs only showing up under the Detail portion of the screen.
I got it working by:
Create a "NoActionBar" style in styles.xml, then refer to it in your main layout using "android:theme="#style/AppTheme".
<!-- Turn off normal application bar so we can put our toolbars where we please.
Do this by replacing "Theme.AppCompat.Light.DarkActionBar" with NoActionBar
per http://www.truiton.com/2015/04/android-action-bar-dialog-using-toolbar/ -->
<style name="AppTheme" parent="MaterialTheme.Base"/>
<style name="MaterialTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="windowNoTitle">true</item>
<!--We will be using the toolbar so no need to show ActionBar-->
<item name="windowActionBar">false</item>
Toss android.support.design.widget.CoordinatorLayout and just use a LinearLayout.
Here is a snippet that has the toolbar containing the tabs only taking up part of the screen real estate rather than the entire width. Note that the toolbar has "app:layout_scrollFlags="scroll|enterAlways":
<FrameLayout android:id="#+id/detail_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="end"
android:layout_weight="2"
tools:name="com.android.bazemom.popularmovies.TabContainerFragment"
>
<!-- second toolbar that will be used for the tabs -->
<android.support.v7.widget.Toolbar
android:id="#+id/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="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways"
/>
<android.support.design.widget.TabLayout
android:id="#+id/tabanim_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<!-- Helps handing the Fragments to load for each Tab -->
<android.support.v4.view.ViewPager
android:id="#+id/tabanim_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
Here is what the Master-Detail view looked like on wide tablet. The tabs are circled in green. The toolbar with an action is above the tabs.

Categories