Month: August 2012

  • How to create custom groupIndicator for ExpandableListView group

    How to create custom groupIndicator for ExpandableListView group

    Here is tutorial How to create custon groupIndicator for ExpandableListView in Andriod.
    Here is screenshot:

    To do it you need:

    1. Create 9-patch images for normal and expanded state
    2. Create selector with this 9-patch images

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_expanded="true" android:drawable="@drawable/group_indicator_expanded" />
        <item android:drawable="@drawable/group_indicator" />
    </selector>

    3. Set this selector as groupIndicator for ExpandableListView

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
        <ExpandableListView
            android:id="@+id/expandableListView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:groupIndicator="@drawable/group_indicator_selector" >
        </ExpandableListView>
    </LinearLayout>

    That’s all.

    Here you can download the source code of sample Android project

    Download it from github
  • How to get sound effect when button clicked in Android or playing with SoundPool

    How to get sound effect when button clicked in Android or playing with SoundPool

    Here I want to share you a simple code.

    If you need to get sound effect for button click or some other event in your Android application you find what you need.

    Below you can download source code of this sample Android project

    Android SDK provide SoundPool class for it. Lets see how it works.
    I’ve created simple application for you. Below you can see screenshot. It is just button which can fire sound effect when it clicked.

    Here is sourcecode of Android activity:

    package com.hrupin.sample.soundeffects;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    
    public class SoundEffectsInAndroidActivity extends Activity implements OnClickListener {
        private Button button;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            // init Effects class
            Effects.getInstance().init(this);
            button = (Button)findViewById(R.id.button1);
            button.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            Effects.getInstance().playSound(Effects.SOUND_1);
        }
    }

    I’ve created Effects class as wrapper for SoundPool.
    Here is sourcecode:

    package com.hrupin.sample.soundeffects;
    
    import java.util.HashMap;
    
    import android.content.Context;
    import android.media.AudioManager;
    import android.media.SoundPool;
    import android.util.Log;
    import android.widget.Toast;
    
    public class Effects {
    
        private static final String TAG = Effects.class.toString();
    
        private static final Effects INSTANCE = new Effects();
    
        // Sound ID can't be 0 (zero)
        public static final int SOUND_1 = 1;
    
        private Effects() {
    
        }
    
        public static Effects getInstance() {
            return INSTANCE;
        }
    
        private SoundPool soundPool;
        private HashMap<Integer, Integer> soundPoolMap;
        int priority = 1;
        int no_loop = 0;
        private int volume;
        float normal_playback_rate = 1f;
    
        private Context context;
    
        public void init(Context context) {
            this.context = context;
            soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
            soundPoolMap = new HashMap<Integer, Integer>();
            soundPoolMap.put(SOUND_1, soundPool.load(context, R.raw.sound_1, 1));
            AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            volume = audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
        }
    
        public void playSound(int soundId) {
            Log.i(TAG, "!!!!!!!!!!!!!! playSound_1 !!!!!!!!!!");
            soundPool.play(soundId, volume, volume, priority, no_loop, normal_playback_rate);
            Toast.makeText(context, "Now you can hear sound effect!", Toast.LENGTH_LONG).show();
        }
    }
    

    Notice, that SOUND_1 constant can’t be 0 (zero).
    That’s all for this sample.
    Please, write comment if you have some questions. Also you can download the full sourcecode.

    Here you can download the source code of simple Android project.

    Download it from github
  • How to open activity by Android WebView hyperlink click or How to handle hyperlink click in Android WebView

    How to open activity by Android WebView hyperlink click or How to handle hyperlink click in Android WebView

    Case 1:
    I have Android WebView with some HTML content. I need to open activity when user click on some hyperlink.

    Case 2:
    I have Android WebView with some HTML content. I need to do something when user click some hyperlink.

    HOW TO DO THIS.

    Below you can download source code of this sample Android project

    1. To do this your WebView must have your custom WebViewClient
    2. Your Android WebView HTML content must have specific hyperlinks.

    Lets see source code of Activity:

    package com.hrupin.sample.webviewintent;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    
    public class SendIntentByHyperlinkClickActivity extends Activity {
        private WebView webView1;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            webView1 = (WebView) findViewById(R.id.webView1);
            String summary = "<html><head><title>Title of the document</title></head><body><h1><a href=\"hrupin://second_activity\">LINK to second activity</a></h1><h1><a href=\"http://www.google.com/\">Link to GOOGLE.COM</a></h1></body></html>";
            webView1.loadData(summary, "text/html", null);
            webView1.setWebViewClient(new MyWebViewClient(this));
        }
    }

    The sourcecode of MyWebViewClient must be something like this:
    Pay attantion in shouldOverrideUrlLoading method.

    package com.hrupin.sample.webviewintent;
    
    import android.content.Context;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.view.KeyEvent;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    
    public class MyWebViewClient extends WebViewClient {
    
        private Context context;
    
        public MyWebViewClient(Context context) {
            this.context = context;
        }
    
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.equals("hrupin://second_activity")) {
                Intent i = new Intent(context, SecondActivity.class);
                context.startActivity(i);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
    }

    That’s all.

    Here you can download source code of sample project to see sample of usage.

    Download it from github
  • How to transfer java class between Android Activities

    How to transfer java class between Android Activities

    There are a lot of ways transferring complex data between Android activities. Lets talking about couple of they. I going to talking about ways which used Bundle as data container.

    1. FIRST. Pascelable interface

    Bundle can contain java class which implemented Parcelable interface. Your class must implement this interface. After that bundle can contains this class.

    2. SECOND. Put as JSON string
    In some cases I transfer data between activities as JSON string.

    This is not finished list of techniques. There are couple of then.

  • How to use custom Truetype font in Android UI or playing with TypeFaces

    How to use custom Truetype font in Android UI or playing with TypeFaces

    Here is the sample of usage:

    Below you can download source code of this sample Android project

    To use custom Truetype font in your Android UI you need.
    1. Download *.TTF file with font.
    2. put this file in assets project’s dir.
    3. You need read this font from assets dir:

    Typeface typeFace = Typeface.createFromAsset(context.getAssets(), "YOUR_FONT.ttf");

    4. set TypeFace for your UI element. In my case it is TextView.

    textView.setTypeface(typeFace);

    Also it works for Button, EditText, etc.
    Full source code of activity:

    package com.hrupin.sample.customfont;
    
    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Typeface;
    import android.os.Bundle;
    import android.widget.TextView;
    
    public class CustomFontInAndroidActivity extends Activity {
        private static Typeface typeFace = null;
        private TextView textView;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            initTypeFace(this);
            textView = (TextView) findViewById(R.id.text);
            textView.setText("Hello, my name is Igor Khrupin.\n\n I can help you in Android development.\n\n Contact me:\n www.hrupin.com");
            textView.setTypeface(typeFace);
        }
    
        public static void initTypeFace(Context context) {
            if (typeFace == null) {
                try {
                    typeFace = Typeface.createFromAsset(context.getAssets(), "AeroviasBrasilNF.ttf");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    Here you can download source code of this sample Android project.

    Download it from github
  • How to create custom Vertical or Horizontal Scrollbar for ListView, ScrollView, etc. in Android

    How to create custom Vertical or Horizontal Scrollbar for ListView, ScrollView, etc. in Android

    Here is the screenshot of my custom Android scrollbar.

    Below you can download source code of this sample Android project

    How do the same.

    It is so simple. To make custom scrollbar for ListView or ScrollView, etc. you need set android:scrollbarThumbVertical or android:scrollbarThumbVertical for in screen layout. Example:

    <listview android:id="@+id/listView1" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        android:scrollbarthumbvertical="@drawable/thumb"/>

    Also it can be used with ScrollView, etc.

    Here you can download source code of sample Android project.

    Download it from github
  • How to make a transparent WebView in Android

    How to make a transparent WebView in Android

    Today one of my subscribers (@prasad) ask me: “how to make a transparent webview behind a gridview.”

    I don’t have complete example for it, but this info might help you.

    Do do transparent WebView I create this layout:

    <?xml version="1.0" encoding="UTF-8"?>
    <!--?xml version="1.0" encoding="utf-8"?-->
    <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:orientation="vertical" 
        android:background="#ff0000">
        
       <webview android:id="@+id/webView1" 
                android:layout_width="match_parent" 
                android:layout_height="match_parent" />
    </linearlayout>

    Notice, that backgroung behind WebView is RED

    And here I have sourcecode of Activity:

    package com.hrupin.transparent_webview;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.webkit.WebView;
    
    public class Transparent_webviewActivity extends Activity {
        private WebView webview;
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            webview = (WebView) findViewById(R.id.webView1);
            // Here is I make transparent background for WebView
            webview.setBackgroundColor(0x00000000);
            String summary = "<h1>The content of the document......</h1>";
            webview.loadData(summary, "text/html", null);
        }
    }

    That’s all.
    It works for me on Android 2.3.3 (Gingerbread). Device is HTC Desire.

  • How to detect when mobile phone received the SMS Message on Android.

    How to detect when mobile phone received the SMS Message on Android.

    To receive SMS messages you need to create BroadcastReceiver for it.

    Below you can download source code of sample Android project

    Here is SmsBroadcastReceiver.java

    package com.hrupin.sample.sms;
    
    import android.content.BroadcastReceiver;
    import android.content.ContentValues;
    import android.content.Context;
    import android.content.Intent;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    import android.telephony.SmsMessage;
    import android.util.Log;
    import android.widget.Toast;
    
    public class SmsBroadcastReceiver extends BroadcastReceiver {
    
        private static final String TAG = SmsBroadcastReceiver.class.getSimpleName();
        public static final String SMS_CONTENT = "sms_content";
    
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "Intent recieved: " + intent.getAction());
    
            Cursor c = context.getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
            c.moveToFirst();
            String smsBody = c.getString(12);
            Toast.makeText(context, "SMS RECEIVED:", Toast.LENGTH_LONG).show();
            Toast.makeText(context, smsBody, Toast.LENGTH_LONG).show();
    
            Intent fireActivityIntent = new Intent(context, SMSDetectorActivity.class);
            fireActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            fireActivityIntent.putExtra(SMS_CONTENT, smsBody);
            context.startActivity(fireActivityIntent);
    
        }
    }

    Also you need specific permissions:

    <uses-permission android:name="android.permission.RECEIVE_SMS">
    <uses-permission android:name="android.permission.READ_SMS">

    Next step is put BroadcastReceiver into AndroidManifest

    <application android:icon="@drawable/ic_launcher" 
        android:label="@string/app_name">
        ..................
        <receiver android:name=".SmsBroadcastReceiver">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED">
                </action>
            </intent-filter>
        </receiver>
    </application>

    Here you can download source code of this sample Android project

    Download it from github