Android Limited Character TextBox Custom CompoundView

Whats is compound view ?

Compound views are nothing but a pre-configured ViewGroups and which can be used as one single unit. You compound view class can extend any ViewGroup in android.

In this tutorial I have tried to explain how you can create a fully customized compound view which can limit length of characters in EditText and also show remaining characters in a TextView.

Step 1: Define and use additional attributes

Create your own attribute file attrs.xml and put it in project as res/values/attrs.xml

An attrs.xml can look like following.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="LimitedCharacterLayout">
 <attr name="inputTextcolor" format="color" />
 <attr name="displayTextColor" format="color" />
 <attr name="maxInputLimit" format="integer" />
 <attr name="numInputLines" format="integer" />
 <attr name="inputTextSize" format="integer" />
 <attr name="displayTextSize" format="integer" />
 <attr name="inputTextStyle">
 <enum name="normal" value="0" />
 <enum name="bold" value="1" />
 <enum name="italic" value="2" />
 <!--attr>
 <attr name="displayTextStyle">
 <enum name="normal" value="0" />
 <enum name="bold" value="1" />
 <enum name="italic" value="2" />
 <!--attr>
 <attr name="inputTextBackground" format="color|reference" />
 <attr name="displayTextBackground" format="color|reference" />
 <attr name="displayTextGravity">
 <enum name="top" value="0x30" />
 <enum name="bottom" value="0x50" />
 <enum name="left" value="0x03" />
 <enum name="right" value="0x05" />
 </attr>
 <attr name="inputTextGravity">
 <enum name="top" value="0x30" />
 <enum name="bottom" value="0x50" />
 <enum name="left" value="0x03" />
 <enum name="right" value="0x05" />
 </attr>
 </declare-styleable>
</resources>

Step 2 : Mention View tags in your layout file layout_main.xml

<com.example.compoundview.LimitedCharacterLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_margin="20dip"
          android:layout_weight="1"
          compound:displayTextColor="@color/bottle_green"
          compound:displayTextGravity="right"
          compound:displayTextStyle="bold"
          compound:inputTextBackground="@drawable/white_rounded_bg"
          compound:inputTextStyle="italic"
          compound:inputTextcolor="@color/blue"
          compound:maxInputLimit="300"
          compound:numInputLines="5" >
 </com.example.compoundview.LimitedCharacterLayout>

Also add xmlns:compound=”http://schemas.android.com/apk/res/com.example.compoundview&#8221; in your parent layout as a namespace.

Step 3 : Getting Value from attributes and assign them to Views.

TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.LimitedCharacterLayout, 0, 0);
input.setLines(a.getInt(R.styleable.LimitedCharacterLayout_numInputLines,MAX_LINES));
This is how one should fetch a parameter from attrs.xml file

I have provided all needed parameters in attrs.xml file, e.g. background color or image,font color, font style etc.

You can download the source code from here.

And running application should look like following screenshots.

With Gravity Right

With Gravity Right

With Gravity Left

With Gravity Left

Android Canvas Painting Demo

Hello Friends,

Working with canvas in andriod. Aaah!!!! so annoying and tough. I was in need to make such thing where user can take picture and do some paint stuff on it like writing text,choosing pen color,undo,redo facility,sketch mode. After spending few hours on google I found some libraries but they were heavy and providing many facilities. So I just decided to do on my own. And here is the effort of two days.

There are three main Activities

1 ) Which allows user to open camera

Image

Open a Camera by pressing this button

2) Activity which takes picture (Yea choose to create my own small camera app)

3) Screen which allows user to draw on image.

Image

Do some Editing and Painting

Image

Do some Editing and Painting

After playing on canvas which has image as a background user can press the done button and show the preview of edited image on home screen.

Image

Preview Of Image Editing.

There are lot of things which I like to explain. But all can not be covered here.Still lets take a brief session.

FingerPaint.java is the class which do all this painting stuff. Few part of it is copied from Android’s FingerPaint example. Others I have completed by writing lot of complicated code.

There is an inner class DrawingPanel in FingerPaint , it handles all the touch event and actions done on canvas. You will find a code for undo,redo too. Implementing there facility is due to maintaining simple ArrayList of PathPoints ArrayList, where PathPoints is a Java Bean.

I am sorry for not providing more optimized and neat code. I will try to beautify the code.

You can also download , source code from here.

The Pianist

Yesterday I was kinda idle. No work to do. So I tried my hand on piano. So I downloaded one cool app from google play.

And start experimenting with the different key and scales. After practice of an hour I am able to play ‘Kal Ho Na Ho’ on piano.

(Well well well, let me know that once upon a time playing keyboard was my passion. Then day after day due to studies and other work I broke up with my this girlfriend ;)  ).

Screen Shot taken from the android app ‘Piano Pro’

Above is a notation chart for the piano. Those ABCD highlights the key which denotes specific scale.  A scale is any sequence of musical notes.

So below are the notes to play Kal Ho Na Ho on piano.


Har Ghadi Badal Rahi Hai Roop Zindagi
C bC bC bCE DC b ab ab
Chaav Hai Kabhi Kabhi Hai Dhoop Zindagi
C bC bC bCE DC b ab ab
Har Pal Yahan Jee Bhar Jiyo
g a Ca f ga g
Jo Hai Sama.... Kal Ho Na Ho
g a Ca f a# a g

———————————————

Chaahe Jo tu Mein Poore Dil Se Milta Hai Woh Mushkil Se
bC F E D ba b C bCF E D bab C
Aisa Jo Kooii Kahin Hai Bas Vohi Sab se Hasin Hai
bc F E DC a b C bC FE D C ab C
Us Haath Ko Tum Thaam Lo Woh Meherbaaaan Kal Ho Na Ho
g aC a f ga g g aa C a f a# a g

I have attached audio below. Listen and enjoy.

Do Comment and Like….

Android WiFi Direct Example

Wi-Fi Direct allows Android 4.0 (API level 14) or later devices with the right hardware to connect directly to each other via Wi-Fi without an intermediate access point. Using these APIs, you can discover and connect to other devices when each device supports Wi-Fi Direct, then communicate over a speedy connection across distances much longer than a Bluetooth connection. This is useful for applications that share data among users, such as a multiplayer game or a photo sharing application.

The WifiP2pManager class provides methods to allow you to interact with the Wi-Fi hardware on your device to do things like discover and connect to peers. The following actions are available:

You can find all set up details http://developer.android.com/guide/topics/connectivity/wifip2p.html

I will try to explain few more things about wi-fi direct.

  • For peer-to-peer data transmission it does not use any kind of traditional home, office or hotspot network.
  • For Security purpose it uses WPA2 encryption protection.
  • It can transfer data at the speed of 2.5 to 3.0 Mbps. (Tested on Galaxy Tab-2 and Nexus 7 Tab)
  • Wi-Fi Direct can operate at up to 100m. Some reference site says 656 feet too.
  • We can also set up group between devices for which hardware support is offered for wifi direct.

Below is the process explained to perform this feature.

  1. Check whether wifi direct is available or not using WifiP2pManager.WIFI_P2P_STATE_ENABLED.
  2. To discover peers that are available to connect to, call discoverPeers() to detect available peers that are in range.
  3. If the discovery process succeeds and detects peers, the system broadcasts the WIFI_P2P_PEERS_CHANGED_ACTION intent, which you can listen for in a broadcast receiver to obtain a list of peers.
  4. When you have figured out the device that you want to connect to after obtaining a list of possible peers, call the connect() method to connect to the device.
  5. To transfer the data it uses Sockets. So combination of ServerSocket and Socket class from network package performs actual sending and receiving of the file.

 

Find a simple example : WifiDemo.zip

Scrolling Tricks in android – Part 2

This is the very first time I posting a new blog back to back. If you are new to this post please refer my previous post Scrolling Tricks in android – Part 1.

And Here I am sharing one more cool scrolling effects example.

1 ) Set up Library Project first.

Download a project from here, and make this project a library project.

To make project a library go to -> Properties -> Android -> Please tick isLibrary at the end of screen.

2) Download a demo project.

You can download a demo project from here. Just set above project as a library project for this project.  Build it and Run it.

Originally Created By : Xavi Rigau

Scrolling Tricks in android – Part 1

Hi Friends,

          While surfing internet I found a very good example of scrolling tricks. Here I am sharing it with you guys.
There are two fragments containing different scrolling effect views. Effects are named as  ’QUICK RETURN’ and ‘STICKY’. For both the kind of effect a separate class is defined named

QuickReturnFragment

and

StickyFragment

.
There is one more class named

ObservableScrollView

which is extending ScrollView.

I have attached screen shot of that.

Also find source code for that here.

Also Visit : Scrolling Tricks in android – Part 2

Originally Created by : Roman Nurik

Swipe To Dismiss ListView

Hello developers,

Here I am sharing a code to perform delete operation on listview  by just swiping it to right or left.

I am swiping on Item 11 in ListView

Effect After Deleting Items

Keep in mind this thing will only work in 4.0 or above. First Download the Demo from here.

After extracting the zip you will find three class file in src project.

1) Main Activity

The Class which displays the view to user and also has listener implementation on button and listview.

2) SwipeDismissTouchListener

This class is responsible to listen swipe over the button’s object.

dismissableButton.setOnTouchListener(new SwipeDismissTouchListener(
 dismissableButton,
 null,
 new SwipeDismissTouchListener.OnDismissCallback() {
 @Override
 public void onDismiss(View view, Object token) {
 dismissableContainer.removeView(dismissableButton);
 }
 }));

3) SwipeDismissListViewTouchListener

This class is responsible to listen swipe over the listview’s item object. In below code snippet just check that we are passing listview object while constructing an object of this class.

SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(
listView,
new SwipeDismissListViewTouchListener.OnDismissCallback() {
@Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
myAdapter.remove(myAdapter.getItem(position));
}
myAdapter.notifyDataSetChanged();
}
});

Both SwipeDismissTouchListener and SwipeDismissListViewTouchListener implements OnTouchListener which listens every touch on particular views.

You can also download source code from here.

Originally Created by : Roman Nuric

Iintegrate RevMob in Android

Android Developers must have heard AdMob. They uses AdMob to monetize their android app.

RevMob is having similar concept but have less line of code and of course more money.

Find a great step by step tutorial here.

Create sqlite database in android using java script

Hi friends,

1 month back I was assigned a project where we need to make our own Phone Gap like mechanism.

You can know more about phone gap here. Basically the project is mixture of HTML5,JavaScript,jQuery and Android-Java.

There are lot of stuff to which I can share with you but which I found most interesting is connecting sqlite database using javascript code. (Yea really !!! I was wondering whether it is possible or not.) After some r&d and help of few I am able to find out the things.

Here are the steps to create database from javascript.

Step 1 : Create a simple android project.

You can name it JavaScriptTest or any name say I hate Java Script :)

Step 2: Create an activity which has webview in it.

public class JavaScriptTestActivity extends Activity {
/** Called when the activity is first created. */
@Override

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView=new WebView(this);
webView.setInitialScale(1);
webView.requestFocus(View.FOCUS_DOWN);
webView.requestFocusFromTouch();

final String databasePath = this.getApplicationContext().getDir(“database”, Context.MODE_PRIVATE).getPath();
WebSettings settings = webView.getSettings();
settings.setDatabasePath(databasePath);
settings.setAppCacheMaxSize(5*1024*1024);
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);
settings.setLoadsImagesAutomatically(true);
settings.setUseWideViewPort(true);
settings.setLoadsImagesAutomatically(true);
settings.setAppCacheEnabled(true);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
settings.setAllowFileAccess(false);
settings.setUseWideViewPort(false);
settings.setSupportZoom(false);
settings.setSavePassword(false);
settings.setSupportMultipleWindows(false);

webView.setWebChromeClient(new WebChromeClient()
{
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}

@Override
public void onExceededDatabaseQuota(String url,
String databaseIdentifier, long currentQuota,
long estimatedSize, long totalUsedQuota,
WebStorage.QuotaUpdater quotaUpdater) {
quotaUpdater.updateQuota(5 * 1024 * 1024);
}
});

// Above lines are necessary to load javascript and allowing your webview to create sqlite database so KEEP THEM AS IT IS.
setContentView(webView);
webView.loadUrl(“file:///android_asset/index.html”);
}

}

Step 3 : Create a Java Script file, named it db.js

Please put above created file in assets folder. db.js will hold content like this . Magic is here :) .

function loaddb()
{
var db = openDatabase(‘testdb’, ’1.0′, ‘my database’, 2 * 1024 * 1024);

db.transaction(function (tx)
{
tx.executeSql(‘CREATE TABLE IF NOT EXISTS person (_id INTEGER, person_name TEXT, address TEXT)’);

tx.executeSql(‘INSERT INTO person (_id, person_name, address) VALUES(1, “Hardik Trivedi”, “Ahmedabad,Gujarat,India”)’);
tx.executeSql(‘INSERT INTO person (_id, person_name, address) VALUES(2, “Sonam Kapoor”, “Mumbai,Maharashtra,India”)’);
tx.executeSql(‘INSERT INTO person (_id, person_name, address) VALUES(3, “Rajnikanth”, “There is no specific address of him :) “)’);

});
}

Step 4 : Create index.html (here also you can create file with any name)

For now index.html is pretty decent page just having two script tag and few html tags

<html>
<head>
<script src=”db.js”></script>
<script src=”jquery.js”></script>

</head>
<body>
<div>
<script language=”javascript”>
$(document).ready(function() {
alert(“Hello”);
loaddb();
});
</script>
</div>
<h4>Hello Friends !!!!!!</h4>
</body >

</html>

In above code I have added two js files. db.js holds function to handle database and jquery.js has $document.ready function’s definition.

Please find sample code here.

Enjoy the concept. Cheers !!!

How to integrate Bing map in android

Special Note : I have received so many queries regarding not running the bing map on 4.0 onward OS version. Bing map uses the WebView to display the map and due to some bug its not showing the map on device. Lets hope Microsoft resolves it ASAP

Hi Folks,

I was just sitting idle in office (No work is assigned in project ;) ).But as you know a developer should not sit idle. Once should keep exploring. So I just start to know bing map in android (Google is no more enjoying monopoly in map business :o ).  There are 3-4 different views like Road Map,Ariel,Bird eye view etc. You will love bird eye view.Graphics are nicer than Google map.I tired this example on HTC sensation I feel its bit laggy. Anyways its has a list of pros and cons but lets start step by step integration of Bing map in android device.

First bookmark bing map site for developer.

Step 1:

  • Now very first requirement to have a windows live id. If you do not have such id create one . Go to map portal and get yourself registered. And if you are already having id sign in using that credentials.

Step 2 :

  • After creating windows live account it will again redirect to one screen where you need to create one account (It’s a formality to identify each map key user.) See below image.

  • Now on left hand side menu click on Create or view keys.

  • Fill required information.
  1. Application Name : Test App
  2. Application URL : Leave the field blank (It’s not compulsory)
  3. Application type : Mobile
  4. Feel CAPTCHA and submit the details.
  • Scroll down a bit you will be able to see a key generated below.

  • Now after this we are done with the registration process.

Step 3 :

  • Now download Bing map SDK from here.
  • You will have a zip file in your downloading dialog. Extract that zip file after downloading and import that in eclipse workspace.

Step 4 :

  • Now what we have to do is to use that key which we have generated few minutes back.
  • Now open Constants.java from package org.bingmaps.app
  • You will be able to see two variables BingMapsKey  and BingSpatialQueryKey replace both variable by values explain below.
  1. BingMapsKey=”Your map key”
  2. BingSpatialQueryKey=”Mobile”

Step 5 :

  • Clean your build and build again. Deploy it on device. (I was not able to test this on simulator so I am not sure whether it will work on simulator or not.)
  • You will be able to see below given screens.

Map View

Open Menu, tap on get direction enter two endpoints and get your map view displayed path over it.

  • I will try to extend this thread by explaining few more things like how to display pin or overlay on it etc.

You can download modified source code from here.

Follow

Get every new post delivered to your Inbox.