Category Archives: ActionBars

How to change title and Subtitle text color and size of ActionBar in Android?

Here is a simple example that shows how you can change title and subtitle textcolor and its size in Android

Method 1
——–

Changing the styles [For support Library]

Go to Values/styles.xml copy this code to change the textcolor and actionbar background color.


<style name="CustomActivityTheme" parent="@style/Theme.AppCompat.Light">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
        <item name="actionBarStyle">@style/MyActionBar</item>
         <item name="android:windowActionBarOverlay">true</item>
        <!-- other activity and action bar styles here -->
</style>
      <!-- style for the action bar backgrounds -->
<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar">
        <item name="android:background">@drawable/actionbar_background</item>
        <item name="background">@drawable/actionbar_background</item>
        <item name="android:titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
        <item name="android:subtitleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
        <item name="titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
        <item name="subtitleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
     </style>
<style name="MyTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance">
        <item name="android:textColor">@color/color_title</item>
        <item name="android:textSize">12sp</item>
</style>
	  
	  

Note : For applying theme if you are not using the Support Library then change the AppCompat to Holo.

i.e make the Below changes in the parent

parent="@android:style/Theme.Holo.Light"

AND

parent="@android:style/Widget.Holo.Light.ActionBar"

AND for title

parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title"

Now Apply this theme in the AndroidManifest.xml, either for the entire application or a particular activity.

For example


 <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/CustomActivityTheme" >
        <activity
            android:name="com.example.actionbarcustomize.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 </application>
	

Make Sure you add the colors in the strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ActionBarCustomize</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>

    <drawable name="actionbar_background">#FF0000</drawable>
    <color name="color_title">#00FF00</color>
	
</resources>

Method 2
———

You can use a simple java code to so this.

getActionBar().setTitle(Html.fromHtml("<font color='#ff0000'>ActionBartitle </font>"));

Note : Change getActionBar() to getSupportActionBar() if you are using the support library for ActionBar.

That’s all.. Now Run the application and see the changes.

How to work in ActionBar support Library.

Hi all

Today’s post is all about working with ActionBar support libraries from Google.
These libraries support from Android 2.1 (API 7).

ActionBar Support Custom

For working with these libraries we have to follow some instructins.

Please follow these steps exactly for setting up a Actionbar support library.

1. Start the Android SDK Manager.
In the SDK Manager window, scroll to the end of the Packages list, find the Extras folder and, if necessary, expand to show its contents.
2. Select the Android Support Library item.
Note: If you’re developing with Android Studio, select and install the Android Support Repository item instead.
3. Click the Install packages… button.

ActionBar Support Installation

After downloading, the tool installs the Support Library files to your existing Android SDK directory. The library files are located in the following subdirectory of your SDK: /extras/android/support/ directory.

Now Open Eclipse and do the following.

Create a library project based on the support library code:

Make sure you have downloaded the Android Support Library using the SDK Manager.
Create a library project and ensure the required JAR files are included in the project’s build path:
Select File > Import.
Select Existing Android Code Into Workspace and click Next.

Browse to the SDK installation directory and then to the Support Library folder. For example, if you are adding the appcompat project, browse to /extras/android/support/v7/appcompat/.

Click Finish to import the project. For the v7 appcompat project, you should now see a new project titled android-support-v7-appcompat.

In the new library project, expand the libs/ folder, right-click each .jar file and select Build Path > Add to Build Path. For example, when creating the the v7 appcompat project, add both the android-support-v4.jar and android-support-v7-appcompat.jar files to the build path.

Right-click the project and select Build Path > Configure Build Path.
In the Order and Export tab, check the .jar files you just added to the build path, so they are available to projects that depend on this library project. For example, the appcompat project requires you to export both the android-support-v4.jar and android-support-v7-appcompat.jar files.
Uncheck Android Dependencies.

Click OK to complete the changes.

AndroidManifest.xml changes
android:minSdkVersion="7"
android:targetSdkVersion="17">

Important
1. To work with support libraries of actionbar you should also have to change the theme to “Theme.AppCompat”.
2. Also your activity should extend ActionBarActivity.

This is all that needed.
After that you can add this actionbar compat library for any number of projects.

Usage.

Instead of using getActionBar(), use should use getSupportActionBar() to point to suppport actionbar libraries.

A sample looks like this.

package com.coderzheaven.actionbartest;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;

import com.example.actionbartest.R;

public class MainActivity extends ActionBarActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		getSupportActionBar().setTitle("ActionBar Support Demo");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

For that you have to make changes in the styles.xml.

This is my styles.xml in which I have made my ActionBar Custom.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/MyActionBar</item>

        <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/MyActionBar</item>
    </style>

    <!-- ActionBar styles -->
    <style name="MyActionBar"
           parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@drawable/blue</item>

        <!-- Support library compatibility -->
        <item name="background">@drawable/blue</item>
    </style>
</resources>

My strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ActionBarTest</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    
    <drawable name="blue">#0000FF</drawable>

</resources>

So you are done.
Go on and run the project.

You can download a sample of Project which contains the ActionBarCompat Library and a sample project which links this library from here.
So when you import it to your eclipse make sure you import two projects included.

How to Create a new theme for ActionBar in Android.

In this post I will be telling you about how to change the default theme of ActionBar with our own custom One.
Here I will be changing the background color, textColor and alpha of default ActionBar.
Let’s see how it is done.

By Checking out the styles.xml you will find that by default it looks like this.

ActionBar Theme

<resources>
 <style name="AppTheme" parent="android:Theme.Light" />
</resources>

Right now, we are using a theme “AppTheme” which is inheriting all the attributes from Theme.Light.
Lets define a new style named “myActionBarTheme”.

Now my styles.xml looks like this.
Note that this time i Just changed “Holo.Light” to just “Holo” for darker theme.
However you can leave it as the old one.

styles.xml

<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <style name="CustomActionBarTheme" parent="android:style/Theme.Holo">
        <item name="android:actionBarStyle">@style/myActionBarTheme</item>
        
    </style>

    <style name="myActionBarTheme" parent="android:style/Widget.Holo.ActionBar">
        <item name="android:background">#FF4444</item>
        <item name="android:titleTextStyle">@style/myActionBarTitleTextStyle</item>
        <item name="android:alpha">1.0</item>
    </style>
     <style name="myActionBarTitleTextStyle" parent="android:style/TextAppearance.Holo.Widget.ActionBar.Title">
        <item name="android:textColor">#FFFFFF</item>
    </style>

</resources>

Now we have to use it right. If we want to apply it to the complete application we can do it like this in the Android Manifest file.

AndroidManifest.xml

<application android:theme="@style/CustomActionBarTheme" >

Or You can apply different ones to different activities also.
In this example I am just changing the ActionBar text color and alpha also.
You can do any customization according to your wish.

What ever we use as background will be strectched to fill the size of the ActionBar , so make sure you will be providing a nine-patch image or an XML.
Here I am using an Xml named “top_bar_bg.xml”

top_bar_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
      <shape>
         <gradient android:angle="90" 
              android:centerColor="#FF0066FF" 
              android:endColor="#FF0066FF" 
              android:startColor="#FF0066FF" />
        </shape>
    </item>
</selector>

More and more ActionBar customizations and tips will be coming in the next updates.
Please visit again or subscribe to coderzheaven.com and also like us on facebook to get quick updates.

PLease leave your valuable comments on this post.

You can download the complete source code from here.

How to create a SearchView with Filter mode in a ListView in Android?

Actually this is fairly simple.
Android by default provides a SearchView class that has the ability to filter.

Filter ListView
Filter ListView

Just look at the XML layout that I am using in this post.
It consists of a SearchView and a ListView. The searchView searches the listview for the matched content.
Click on the link to download the code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    <SearchView
            android:id="@+id/search_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    <ListView
            android:id="@+id/list_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"/>

</LinearLayout>

Now the Java class or the activity that implements the searchFilter.

package com.coderzheaven.searchviewwithfilter;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;

/**
 * Shows a list that can be filtered in-place with a SearchView in non-iconified mode.
 */
public class SearchViewFilterMode extends Activity implements SearchView.OnQueryTextListener {

    private SearchView mSearchView;
    private ListView mListView;

    private final String[] mStrings = Cheeses.sCheeseStrings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);

        setContentView(R.layout.searchview_filter);

        mSearchView = (SearchView) findViewById(R.id.search_view);
        mListView = (ListView) findViewById(R.id.list_view);
        mListView.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                mStrings));
        mListView.setTextFilterEnabled(true);
        setupSearchView();
    }

    private void setupSearchView() {
        mSearchView.setIconifiedByDefault(false);
        mSearchView.setOnQueryTextListener(this);
        mSearchView.setSubmitButtonEnabled(true); 
        mSearchView.setQueryHint("Search Here");
    }

    public boolean onQueryTextChange(String newText) {
        if (TextUtils.isEmpty(newText)) {
            mListView.clearTextFilter();
        } else {
            mListView.setFilterText(newText.toString());
        }
        return true;
    }

    public boolean onQueryTextSubmit(String query) {
        return false;
    }
}

Click to download the source code from here.

ActionBar with Search Option and other options in Android.

I have already shown some examples with ActionBar.
This is the example showing how to start with ActionBar in android.

1. Android removes the need of Menu button from devices with ActionBar.

2. How to start with ActionBar in Android?

3. Dynamically Adding, Removing, Toggling and Removing all ActionBar Tabs in Android – Part 2?

Now today I will show you another example in which we will put a searchbar along with other buttons in the ActionBar and Listen to the search and Listen to the button select.

This is how we do this.

Take a look at the screenshot.

ActionBar

ActionBar

ActionBar

ActionBar

First in your project “res” folder create a folder named “menu”. the create an xml inside this folder named “actions.xml”.
Now copy these to this xml.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/action_search"
          android:icon="@android:drawable/ic_menu_search"
          android:title="Action Bar Search"
          android:showAsAction="ifRoom"
          android:actionViewClass="android.widget.SearchView" />
    <item android:id="@+id/action_add"
          android:icon="@android:drawable/ic_menu_add"
          android:title="Action Bar Add" />
    <item android:id="@+id/action_edit"
          android:icon="@android:drawable/ic_menu_edit"
          android:showAsAction="always"
          android:title="Action Bar Edit" />
    <item android:id="@+id/action_share"
          android:icon="@android:drawable/ic_menu_share"
          android:title="Action Bar Share"
          android:showAsAction="ifRoom" />
</menu>

OK now we go to the java code. In your Activity file copy this code.

package com.coderzheaven.actionbarsearch;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;
import android.widget.Toast;

public class ActionBarWithSearch extends Activity  implements OnQueryTextListener {
    TextView mSearchText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSearchText = new TextView(this);
        mSearchText.setPadding(10, 10, 10, 10);
        mSearchText.setText("Action Bar Usage example from CoderzHeaven");
        setContentView(mSearchText);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.actions, menu);
        SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setOnQueryTextListener(this);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean    onOptionsItemSelected       (MenuItem item) {
        Toast.makeText(this, "Selected Item: " + item.getTitle(), Toast.LENGTH_SHORT).show();
        return true;
    }

    // The following callbacks are called for the SearchView.OnQueryChangeListener
    public boolean onQueryTextChange(String newText) {
        newText = newText.isEmpty() ? "" : "Query so far: " + newText;
        mSearchText.setText(newText);
        mSearchText.setTextColor(Color.GREEN);
        return true;
    }

    public boolean      onQueryTextSubmit      (String query) {
        //Toast.makeText(this, "Searching for: " + query + "...", Toast.LENGTH_SHORT).show();
        mSearchText.setText("Searching for: " + query + "...");
        mSearchText.setTextColor(Color.RED);
        return true;
    }
}

Here “onQueryTextChange” function Listens to the search textbox when we type and “onQueryTextSubmit” function Listens when we hit search in the keyboard.

PLease leave your comments.

Dynamically Adding, Removing, Toggling and Removing all ActionBar Tabs in Android – Part 2?

Hi all..

In today’s post I will show you how to add actionbar tabs dynamically, remove one by one , hide and unhide them, removing all tabs at once etc.

This simple java code does that.

First create a project and in the MainActivity, paste this.

package com.coderzheaven.actionbartabs;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.action_bar_tabs); 
    }

    public void onAddTab(View v) {
        final ActionBar bar = getActionBar();
        final int tabCount = bar.getTabCount();
        final String text = "Tab " + tabCount;
        bar.addTab(bar.newTab()
                .setText(text)
                .setTabListener(new TabListener(new TabContentFragment(text))));
    }

    public void onRemoveTab(View v) {
        final ActionBar bar = getActionBar();
        if(bar.getTabCount() > 0)
        	bar.removeTabAt(bar.getTabCount() - 1);
    }

    public void onToggleTabs(View v) {
        final ActionBar bar = getActionBar();

        if (bar.getNavigationMode() == ActionBar.NAVIGATION_MODE_TABS) {
            bar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
            bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE);
        } else {
            bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
            bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
        }
    }

    public void onRemoveAllTabs(View v) {
        getActionBar().removeAllTabs();
    }

    /**
     * A TabListener receives event callbacks from the action bar as tabs
     * are deselected, selected, and reselected. 
     **/
    private class TabListener implements ActionBar.TabListener {
        private TabContentFragment mFragment;

        public TabListener(TabContentFragment fragment) {
            mFragment = fragment;
        }

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            ft.add(R.id.fragment_content, mFragment, mFragment.getText());
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            ft.remove(mFragment);
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            Toast.makeText(MainActivity.this, "Reselected!", Toast.LENGTH_SHORT).show();
        }
    }

    private class TabContentFragment extends Fragment {
        private String mText;

        public TabContentFragment(String text) {
            mText = text;
        }

        public String getText() {
            return mText;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View fragView = inflater.inflate(R.layout.action_bar_tab_content, container, false);

            TextView text = (TextView) fragView.findViewById(R.id.text);
            text.setText(mText);

            return fragView;
        }
    }
}

You may be getting many errors, we will be resolving all that in just a few minutes.

Now create an xml named “action_bar_tabs.xml” inside the res/layout folder and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">
    <FrameLayout android:id="@+id/fragment_content"
                 android:layout_width="match_parent"
                 android:layout_height="0dip"
                 android:layout_weight="1" />
    <LinearLayout android:layout_width="match_parent"
                  android:layout_height="0dip"
                  android:layout_weight="1"
                  android:orientation="vertical">
        <Button android:id="@+id/btn_add_tab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Add Tab"
                android:onClick="onAddTab" />
        <Button android:id="@+id/btn_remove_tab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Remove Tab"
                android:onClick="onRemoveTab" />
        <Button android:id="@+id/btn_toggle_tabs"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Toggle Tabs"
                android:onClick="onToggleTabs" />
        <Button android:id="@+id/btn_remove_all_tabs"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Remove All Tabs"
                android:onClick="onRemoveAllTabs" />
    </LinearLayout>
</LinearLayout>

Now create another xml for the tab content and named it “action_bar_tab_content.xml” and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/text"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" />

OK Done. Go on and run it.

ActionBar Tabs

ActionBar Tabs

ActionBar Tabs

ActionBar Tabs

Download Source code from here

Download.

Please leave your valuable comments now

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

How to start with ActionBar in Android?

With Android 3.0 Google eliminated the need of hardware menu button which is replaced by Action Bars.

Here is a quick example on how to use ActionBars.

Action Bar in Android

First create a new project and name it ActionBarExample.

Now create a folder named “menu” in res folder and create a new XML file inside it named “action_bar_menu.xml”.

action_bar_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/menuitem1" android:showAsAction="ifRoom" android:title="Test1"></item>
    <item android:id="@+id/menuitem2" android:showAsAction="ifRoom" android:title="Test2"></item>
</menu>

Now the java code for implementing this ActionBar.

MainActivity.java

package com.example.actionbarexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends Activity {
	@Override
	  public void onCreate(Bundle savedInstanceState) {   
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_main);
	  }

	  @Override
	  public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.action_bar_menu, menu);
	    return true;
	  }

	  @Override
	  public boolean    onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.menuitem1:
	      Toast.makeText(this, "Test 1 Clicked", Toast.LENGTH_SHORT).show();
	      break;
	    case R.id.menuitem2:
	      Toast.makeText(this, "Test 2 Clicked", Toast.LENGTH_SHORT).show();
	      break;

	    default:
	      break;
	    }

	    return true;
	  }
	} 

As there is enough space in the ActionBar otherwise you may see the Overflow menu or you have to use the Option menu button on your phone.

Please leave your comments om this post.