Saturday, April 27, 2013

Android Get Application Context

0 comentarii
When we are inside an Activity, and we need the application context we can use getApplicationContext () method. But what if we are not inside an Activity and we need the application context? Well, I will explain in this tutorial how you can get the context of the application outside an Activity.


You have to create a new class called "ApplicationContextProvider" which will provide the context wherever in the application. The code looks like this:
    import android.app.Application;
    import android.content.Context;
    
    
    public class ApplicationContextProvider extends Application {
    
        /**
         * Keeps a reference of the application context
         */
        private static Context sContext;
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            sContext = getApplicationContext();
    
        }
    
        /**
         * Returns the application context
         *
         * @return application context
         */
        public static Context getContext() {
            return sContext;
        }
    
    }
    
    
    Now you have to declare this class in the AndroidManifest.xml in the application tag:
<application android:name=".ApplicationContextProvider" 
             android:label="@string/app_name">
















And that's all. You can get now the application context wherever you need it by simply calling

ApplicationContextProvider.getContext();
Continue reading →
Monday, April 22, 2013

Set custom font on android - from assets

3 comentarii
Among other nice things that Android has, we can also load custom fonts.
To do that we need to get a font file with the desired font. There are some sites where you can find open source fonts like this or this.

Ok, I assume you downloaded this font file angrybirds-regular.ttf .

Step 1:
- put the font file in the android assets directory

Step 2:

Create an util class that we will use it when we need to load our font:


/**
 * Used to load fonts from the assets directory
 *
 * @author Catalin Prata
 *         Date: 04/22/13
 */
public class FontUtils {

    // font file name
    public static final String FONT_ANGRY_BIRDS = "angrybirds-regular.ttf";

    // store the opened typefaces(fonts)
    private static final Hashtable<String, Typeface>  mCache = new Hashtable<String, Typeface>();

    /**
     * Load the given font from assets
     *
     * @param fontName font name
     * @return Typeface object representing the font painting
     */
    public static Typeface loadFontFromAssets(String fontName) {

        // make sure we load each font only once
        synchronized (mCache) {

            if (! mCache.containsKey(fontName)) {

                Typeface typeface = Typeface.createFromAsset(ApplicationProvider.context().getAssets(), fontName);

                mCache.put(fontName, typeface);
            }

            return mCache.get(fontName);

        }

    }

}



Step 3:
- use the font load method to set the font of a TextView:

// I assume that myTextView is an instance of a TextView class and it is the text view that I want to have the custom font
myTextView.setTypeface(FontUtils.loadFontFromAssets());



When you use custom fonts and load them from the assets multiple times you might get some crashes, with the class above, you won't have any problems.

I hope it will help you! :)

Continue reading →
Saturday, April 6, 2013

Android ExpandableListView Add Footer Dynamically

0 comentarii
Hi, recently I ran into a problem with footer view on an ExpandableListView. I wanted to add a footer view only when I would have needed it. I tried many ways to achieve this, but the only way that worked, in my case, was to add the footer and just after it to remove it, and only after this "trick" was done, I could add the footer anywhere in the code.

So I will show in this tutorial how I did this. It's very simple :)

1. First you have to follow the steps from Android ExpandableListView Example, but when you will get to "MyActivity" class you will have to ignore it and follow the steps from this tutorial. So, you must create all the classes from that tutorial except "MyActivity" which will be created here.

2. Create a new xml file under res-layout, called "footer_view.xml". The code is below:
<?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="wrap_content"
              android:id="@+id/footer_layout">

    <TextView android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:id="@+id/footer_view_id"
              android:text="I am the footer view :D"/>
</LinearLayout>


3. Now create the "MyActivity" class:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.util.ArrayList;

public class MyActivity extends Activity {

    private ExpandableListView mExpandableList;
    private LinearLayout footerLayout;

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


        mExpandableList = (ExpandableListView) findViewById(R.id.expandable_list);

        ArrayList<Parent> arrayParents = new ArrayList<Parent>();
        ArrayList<String> arrayChildren;

        //here we set the parents and the children
        for (int i = 0; i < 2; i++) {
            //for each "i" create a new Parent object to set the title and the children
            Parent parent = new Parent();
            parent.setTitle("Parent " + i);

            arrayChildren = new ArrayList<String>();
            for (int j = 0; j < 2; j++) {
                arrayChildren.add("Child " + j);
            }
            parent.setArrayChildren(arrayChildren);

            //in this array we add the Parent object. We will use the arrayParents at the setAdapter
            arrayParents.add(parent);
        }

        View view = getLayoutInflater().inflate(R.layout.footer_view, mExpandableList, false);

        footerLayout = (LinearLayout) view.findViewById(R.id.footer_layout);

        // Add the footer before the setAdapter() method
        mExpandableList.addFooterView(footerLayout);

        //sets the adapter that provides data to the list.
        mExpandableList.setAdapter(new MyCustomAdapter(MyActivity.this, arrayParents));

        // Now that we are after the setAdapter() method we have to remove the added footer.
        mExpandableList.removeFooterView(footerLayout);

        // Now that this trick is done, we can use the addFooterView() whenever we want in the code.
        displayFooterAfterDelay();

    }

    /**
     * Displays the footer on the screen after 3 seconds.
     */
    private void displayFooterAfterDelay(){
        // We create a thread that will sleep for 3 seconds.
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // 3 seconds have passed so we have to make the adapter to be displayed on the screen.
                // The UI elements cannot be displayed on this thread so we have to make them to be displayed
                // on the MAIN THREAD. To do this we have to use the "runOnUiThread() method"
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MyActivity.this, "Footer displayed!", Toast.LENGTH_SHORT).show();
                        mExpandableList.addFooterView(footerLayout);
                    }
                });

            }
        }).start();
    }
}


So that's it. The footer will appear after 3 seconds (3000 ms) on the screen. You can also try to make the footer gone at first (before setAdapter) and in the thread to make it visible. If it works this way, I recommend this approach. But for some reason, in my case it didn't work, so I had to use the approach described in this tutorial.

I hope that this tutorial will help anybody who ran into the same problem as me :)


Continue reading →