Custom title for your apps

The default title bar for the apps might not suit the theme of your app. You also might want to add a few more things to the title bar which the default title bar doesn’t help you with. This example will help you develop your own Title Widget which you can directly embed in your layouts containing a left icon, a title text and a progress bar. You can also control the contents of these three widgets and change it as required in your activities. Here we go.

1. The first thing you should do is to switch off the default title. You can do this easily by specifying in your AndroidManifest.xml file that do not intend to use it.

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
    package=”com.beanie.samples.titlewidget” android:versionCode=”1″
    android:versionName=”1.0″>
    <application android:icon=”@drawable/icon” android:label=”@string/app_name”
        android:theme=”@android:style/Theme.NoTitleBar”>
        <activity android:name=”.TitleWidgetActivity”
         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>
    <uses-sdk android:minSdkVersion=”4″ />
</manifest>

Here, in the application tag, set the theme of your app to use the NoTitleBar theme.

2. Create a title_widget.xml which would be the custom layout for your title bar. You can technically add any number of widgets here and finally display it with your custom title. As an example, we will add an ImageView, a TextView and a ProgressBar here.

3. Create a TitleWidget.java class which extends LinearLayout(you can use any Layout) which loads this layout file and exposes methods to modify the contents of the widgets.

4. Add the TitleWidget class as the first view in all your activity layouts’ files to display your custom title bar.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 <com.beanie.samples.titlewidget.TitleWidget
android:id="@+id/titleWidget"
  android:layout_width="fill_parent"
android:layout_height="wrap_content">
 </com.beanie.samples.titlewidget.TitleWidget>
</LinearLayout>

5. Now, in your activity, you can initialize this TitleWidget as any view, since it is a LinearLayout now, and can control the contents of all the widgets.

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Initialize title Widget
        TitleWidget titleWidget = (TitleWidget)
                             findViewById(R.id.titleWidget);

        // Call the methods to change the underlying widgets
        titleWidget.setTitle("My Custom Title");
        titleWidget.setIcon(R.drawable.icon);
        titleWidget.showProgressBar();
        titleWidget.hideProgressBar();
    }

Now you have your own custom title. On the surface, it doesn’t actually feel like a title bar, and yes, it isn’t. It’s just a custom view, that you are trying to make it look like a title bar. Remember!! We switched off the titles by specifying that our app’s theme to “NoTitleBar”. :)
You can find the whole source code here.

Using Custom fonts on Android

I had to do this for a project that I am working on, and I felt that it wasn’t possible to achieve this. Well, there are several examples on the internet regarding this and nothing seemed to be working for me. So, in this post, we will see how to use custom fonts for your application on Android.

Few things before we start off:

  • Not all fonts are compatible with Android
  • You need to package the ttf files with your apk
  • It’s obviously a little bit of extra work

So for this example, we have a TextView and a Button with different fonts. To be able to use your custom font everywhere, ie, on all the TextView and Button widgets in your app, you will have to extend these classes to create your own TextView and Button classes. I have named them as MyTextView and MyButton. And then, I can use these buttons in my layout xml files, with the fully-qualified name of my custom classes.

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
    android:orientation=”vertical” android:layout_width=”fill_parent”
    android:layout_height=”fill_parent”>

    <com.beanie.samples.customfont.MyTextView
        android:layout_marginTop=”10dip” android:id=”@+id/textView”
        android:layout_width=”fill_parent” android:layout_height=”wrap_content”
        android:text=”@string/hello” android:textSize=”20sp”></com.beanie.samples.customfont.MyTextView>

    <com.beanie.samples.customfont.MyButton
        android:layout_marginTop=”10dip” android:id=”@+id/textView”
        android:layout_width=”fill_parent” android:layout_height=”wrap_content”
        android:text=”@string/hello” android:textSize=”20sp”></com.beanie.samples.customfont.MyButton>
</LinearLayout>

In both these classes, we have a method called init() which is called from all the constructors. The method is just 3 line long.

        if (!isInEditMode()) {
                  Typeface tf = Typeface.createFromAsset(getContext().getAssets(), “fonts/ds_digib.ttf”);
                  setTypeface(tf);
        }

Simple!!! You might notice that there is an if condition. This is not required, but it does help when you are preparing your layouts on eclipse, and you need to keep checking if everything’s fine. This method, isInEditMode() returns true while eclipses tries to render the view from the XML.

This is what the documentation says:

Indicates whether this View is currently in edit mode. A View is usually in edit mode when displayed within a developer tool. For instance, if this View is being drawn by a visual user interface builder, this method should return true. Subclasses should check the return value of this method to provide different behaviors if their normal behavior might interfere with the host environment. For instance: the class spawns a thread in its constructor, the drawing code relies on device-specific features, etc. This method is usually checked in the drawing code of custom widgets.

If you don’t put this condition, the layout editor will complain about not being able to set the TypeFace. So, in the layout editor, you will see your TextView and Button widgets with the default font. But, when you run your app on an emulator or a device, you can see the goodness of your custom fonts.

The source code for the sample project can be found here. You can find 3 different fonts (ttf file) in the assets folder to play with.

Getting animations to work

This is a simple project that will explain how to use animations in android through AnimationDrawable. The documentation was a bit outdated. But you might hit a dead-end if you try to call the animation’s start method from within any of the Activity’s life-cycle methods.

In this example, there is an ImageView with it’s “src” value set to an image. The ImageView‘s background is set with you own AnimationDrawable, basically an xml in your res/drawable folder. In the activity, the ImageView has a click listener, which creates an AnimationDrawable from the ImageView’s background, and just calls the start method of the AnimationDrawable class.

Here is a sample AnimationDrawable described through XML.

<?xml version=”1.0″ encoding=”utf-8″?>
<animation-list xmlns:android=”http://schemas.android.com/apk/res/android”
    android:oneshot=”false”>
    <item android:drawable=”@drawable/black” android:duration=”200″ />
    <item android:drawable=”@drawable/cyan” android:duration=”200″ />
    <item android:drawable=”@drawable/green” android:duration=”200″ />
    <item android:drawable=”@drawable/magenta” android:duration=”200″ />
    <item android:drawable=”@drawable/navy” android:duration=”200″ />
    <item android:drawable=”@drawable/orange” android:duration=”200″ />
    <item android:drawable=”@drawable/pink” android:duration=”200″ />
    <item android:drawable=”@drawable/white” android:duration=”200″ />
    <item android:drawable=”@drawable/yellow” android:duration=”200″ />
</animation-list>

And here is the code that gets your animation started.

imageView = (ImageView) findViewById(R.id.ImageButton01);
        imageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                AnimationDrawable animator = (AnimationDrawable) imageView.getBackground();
                imageView.setImageDrawable(null);
                animator.start();
            }
        });

One point to notice is that, you have to remove the ImageView’s “src” value, so that the animation is visible, since the animation works by changing the background of the ImageView, else, your animation would be blocked by the ImageView’s “src” image.

Once you are done, you can stop the animation, and reset the ImageView’s “src” to it’s original image.

// Call this method to stop the animation
    public void stopAnimation(){
        AnimationDrawable animator = (AnimationDrawable) imageView.getBackground();
        animator.stop();
        imageView.setImageResource(R.drawable.icon);
    }

 You can find the whole source code for this example here.

ExpandableListView on Android

ListView is pretty widely used. There are situations when you would like to group/categorize your list items. To achieve such a thing on Android, you would probably use the ExpandableListView. The data to the ExpandableListView is supplied by a special kind of adapter called the SimpleExpandableListAdapter which extends the BaseExpandableListAdapter.

As with any other widget on Android, you are free to customize the widgets as per your needs. Here, I will show how to create such a custom list adapter for the ExpandableListView.

For this example, I want to show a list of vehicles with their names. Also, I want to group them according to their category.

I have 4 classes.
1. Vehicle : The parent class for the rest.
2. Car: Extends the Vehicle class.
3. Bus: Extends the Vehicle class.
4. Bike: Extends the Vehicle class.

I have a method called getRandomVehicle(String name) which returns a random vehicle instance setting the name that I pass. The vehicle can be a Bus, Car or a Bike. Its completely random.

In the ExpandableListAdapter, (the custom adapter), there’s a method called addItem(Vehicle vehicle), which manages the groups and their children.

In the SampleActivity, I have initialized a blank ExpandableListAdapter and set it to the list view. Now, I start a thread, which gets a random vehicle after every 2 seconds, and adds it to the adapter, and calls the adapter to notify that the data has changed.

There are a few methods, in the ExpandableListAdapter, which you should go through carefully. I have two layout files, group_layout.xml and child_layout.xml which are used as the layout for the group views and the child views of the ExpandableListView.

There you go, you have a custom ExpandableListView. You can find the full source code for this example here, ready to run.

There are some more methods that you might be interested in, like, how to change the “arrow icon” for the group views(official doc link), or how to expand or collapse a group at will, or how to handle specific events like group collapsed or group expanded. Read the docs on ExpandableListView.

SDK Tools – ADT Plugin updated

Here comes a new update to the ADT plugin for eclipse and SDK tools.

After you update the SDK tools(r7) from the Android SDK manager or otherwise, you would be prompted to update the ADT plugin(0.9.8) as well. Go for it, and you will see quite a few changes.

In the SDK Tools:
http://developer.android.com/sdk/tools-notes.html 

In the ADT Plugin:
http://developer.android.com/sdk/eclipse-adt.html

For SDK Tools
– Support for library projects.
– Support for aidl files in library projects
– Support for extension targets in Ant build to perform tasks between the normal tasks
– Support for “headless” SDK update 
– Fixes location control in DDMS to work in any locale not using ‘.’ as a decimal point

For ADT Plugin
– Rename package : One click change of project’s package
– Support for library projects that don’t have a source folder called src/
– Support for library projects that depend on other library projects
– Support for additional resource qualifiers: car/desk, night/notnight and navexposed/navhidden
– Adds more device screen types in the layout editor. (Nice)
– Fixes problems with handling of library project names

The most important update for me is the inclusion of more layout editor configurations by default. My last post on creating different configurations for different screen sizes here was just an example to create a configuration for working with different screen sizes at design time. It’s a bonus that they are now included in there by default.

Once click package renaming is also a nice feature, in case you want to fork your project into different versions. Check them out.