Changing Action Bar Colour Programmatically may cause nullPointerException? - java

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

Related

Tablayout animation like whatsapp

I am using TabLayout and SearcView. How can I do , when click search button to hide tab layout like whatsapp.
I try setEnabled method but it can't work properly.
I also used Visibility,setActivated method.What can I do?I don't know. I must use setAnimation method or something else?
MainActivity.java
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private CoordinatorLayout coordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout = (CoordinatorLayout)findViewById(R.id.root_view);
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager)findViewById(R.id.view_pager);
setUpViewPager(viewPager);
tabLayout = (TabLayout)findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setUpViewPager(ViewPager viewPager) {
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragment(CurrencyFragment.getInstance(),"Tracker"); // `CurrencyFragment.getInstance()` should be in `FragmentPagerAdapter.getItem()`
viewPagerAdapter.addFragment(ConvertFragment.getInstance(),"Converter"); // `ConvertFragment.getInstance()` should be in `FragmentPagerAdapter.getItem()`
viewPager.setAdapter(viewPagerAdapter);
}
activity_main.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/root_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
app:titleTextColor="#android:color/white"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</android.support.design.widget.CoordinatorLayout>
If you have used menu item for search then you have to follow below code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.search) // set your own id if you have different id from search.
{
tabLayout.setVisibility(View.GONE);
return true;
}
return super.onOptionsItemSelected(item);
}
When you finished with search then set tablayout visible.
tabLayout.setVisibility(View.VISIBLE);
Follow these simple steps
In your XML file create Appbar. Inside that create a Constraintlayout and keep it as match parent match parent.
Inside that keep your toolbar at the top and below that your tab layout.
Now Create the Edittext of search view as WhatsApp and keep it also as Top_to_top of parent and make the view View. Gone.
In Activity on click of the search icon
toolbar.setVisibility(View.GONE);
tabLayout.setVisibility(View.GONE);
searchViewEditText.setVisibility(View.GONE);

How to Set Icon to display on the far right in Java

getSupportActionBar().setLogo(R.drawable.addicon);
The code above seems to place my Icon in the Centre . I would like to place to the far right and make it clickable as well . At the moment it the image for the icon is in the project files as a drawable I have not included it in any xml files.
You can set android:layoutDirection="rtl" in your toolbar xml for place it to right and
set below code for clickable :
getSupportActionbar().setDisplayHomeAsUpEnabled(true);
and :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//Do stuff
return true;
default:
return super.onOptionsItemSelected(item);
}
}
There are 2 approaches for doing that.
Option Menus
Creating custom toolbar.
With Option Menus
create main.xml under res/menu.
<menu 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"
tools:context="com.ioa.MainActivity" >
<item
android:id="#+id/action_addition"
android:icon="#drawable/addicon"
android:orderInCategory="100"
android:title="Addition"
app:showAsAction="always"/>
</menu>
and inside your activity create menu like,
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
you can perform Action on particular menu item.
#Override
public boolean onOptionsItemSelected(MenuItem Item) {
if (Item.getItemId() == R.id.action_addition) {
// perform action
}
return super.onOptionsItemSelected(paramMenuItem);
}
With custom toolbar
Create your ToolBar like this,
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/ColorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/add"
android:layout_width="46dp"
android:layout_height="46dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="4dp"
android:clickable="true"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
and now you can perform click event of particular ImageView.
ImageView add = (ImageView) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do work.
}
});
happy Coding.
You Need 3 Things:
A Custom Toolbar Layout
Include the toolbar in your activity
Set the Logo to the toolbar
Create new Resource Layout:
include_toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="?attr/colorPrimaryDark"
android:id="#+id/include_toolbar"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
Change Your Activity File: MainActivity.java
public class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar)findViewById(R.id.include_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.mipmap_ic_launcher);
}
}
And here's the styles.xml:
<!-- language: xml-->
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
</resources>

Custom toolbar on android navigation drawer

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

DrawerLayout always returning null when resuming application?

I have a problem when resuming my application. I can create my activity just fine but for some reason when I put my app in the background, wait a few minutes, then have it come back to the foreround DrawerLayout, is always null. The first time when I load my application it seems to work fine but I can't seem to figure out what is going wrong when I re-create the activity from the background. Here is my code:
MainActivity.Java:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Listen for navigation events
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){
public void onDrawerOpened(View view) {
super.onDrawerOpened(view);
...
}
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
...
}
System.out.println("Toolbar: " + toolbar);
System.out.println("Drawer: " + drawer);
System.out.println("Toggle: " + toggle);
drawer.setDrawerListener(toggle);
toggle.syncState();
}
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"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
android:fitsSystemWindows="true" tools:openDrawer="start">
<include layout="#layout/app_bar_news_feed" android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/app_bar_main" />
<include layout="#layout/include_progress_overlay"/>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
layout="#layout/nav_header_friends_list"
android:id="#+id/navigation_header"/>
<ListView
android:id="#+id/friends_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
The first time the application loads, I can successfully print out an object when I print out "Drawer: ", but when I set it to the background then have it come back to the foreground after a few minutes, it seems to print out null and I have no idea why. Any help would be appreciated. Thanks!
You would have to Re-Inflate your XML layout like this.
Try this so this is 2 lines, replace your setContentView
First get the View Group
ViewGroup container = (ViewGroup)view.getParent();
Now we need to Inflate your XML
setContentView(View.inflate(getApplicationContext(),R.layout.yourlayout,container));

Transparent action bar in actionbarshearlock activity

i am using actionbarshearlock library in my project.
I want the action bar to be transparent.
How to do it?
thanks in advance.
without use actionbarshearlock:
just add this line: requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
before setContentView(R.Layout.Test) in onCreate
and this line give you TRANSPARENT ActionBar
getActionBar().setBackgroundDrawable(
getResources().getDrawable(R.drawable.ab_bg_black));
like:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.activity_main);
getActionBar().setBackgroundDrawable(
getResources().getDrawable(R.drawable.ab_bg_black));
}
for R.drawable.ab_bg_black just add drawable colour in string.xml like:
<drawable name="ab_bg_black">#80000000</drawable>
same way using actionbarshearlock:
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(SampleList.THEME); //Used for theme switching in samples
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
super.onCreate(savedInstanceState);
setContentView(R.layout.overlay);
//Load partially transparent black background
getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.ab_bg_black));
}
Edited: Start listview After Actionbar.
if you are using actionbarshearlock then just do like below:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="?actionBarSize" >
</ListView>
</LinearLayout>
try this code, but I'm not sure that is exactly what you need:
bar.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

Categories