Tuesday 29 January 2013

Android custom Edittext (Note Book like editor)























Step1)First Create a class called NoteBook 


package com.amit.notebook;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.EditText;



public class NoteBook extends EditText {
    private Rect mRect;
    private Paint mPaint;

    // we need this constructor for LayoutInflater
    public NoteBook (Context context, AttributeSet attrs) {
        super(context, attrs);

        mRect = new Rect();
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(0x800000FF);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int count = getLineCount();
        Rect r = mRect;
        Paint paint = mPaint;

        for (int i = 0; i < count; i++) {
            int baseline = getLineBounds(i, r);

            canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
        }

        super.onDraw(canvas);
    }
}

Step 2) main.xml

<?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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <com.amit.notebook.NoteBook 
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/notebook">
        </com.amit.notebook.NoteBook >

</LinearLayout>

Step3)

package com.amit.notebook;

import com.note.book.R;
import android.app.Activity;
import android.os.Bundle;

public class NoteBookActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Click here to Dowload Code



Android checking the Density of the device and Version of an Application.


In order to get Device Density simply call the getScreenDensity() and version using 
getVersionName().

Create a class Utility and define given two static method and that can be access by YourClassname.getScreenDensity(this)

as well as YourClassname.getVersionName(this)

1) Device Density

/**
* Check the device density
*
* @param context
*   is current Activity
*/
public static String getScreenDensity(Context context) {
String denstity = null;
DisplayMetrics metrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay()
.getMetrics(metrics);
switch (metrics.densityDpi) {
case DisplayMetrics.DENSITY_LOW:
denstity = "Low";
break;
case DisplayMetrics.DENSITY_MEDIUM:
denstity = "Medium";
break;
case DisplayMetrics.DENSITY_HIGH:
denstity = "High";
break;
default:
denstity = "Ehigh";
break;
}
Log.d(TAG, "getScreenDensity=" + metrics.densityDpi);
return denstity;
}

2) Version Name

/**
* Check the device version mane
*
* @param context
* is current Activity
*/
public static String getVersionName(Context context) {
PackageInfo pinfo;
String versionName = null;
try {
pinfo = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
versionName = pinfo.versionName;
} catch (NameNotFoundException e) {
versionName = "Name Not Found";
}
return versionName;

}

Android conversion of Bitmap to Rounded corner Bitmap.

In order to convert bitmap into rounded corner Bitmap, Just call this given method . This will return rounded corner bitmap.
getRoundedCornerBitmap() Method having two parameter
1) Bitmap
2) int pixel(Radius of corner edge say 10)


/**
* Convert bitmap into rounded corner Bitmap
* @param value
*  Bitmap value to convert
  * @param value
  *  int value in terms of radius to make corner edge
* @return A Rounded corner Bitmap.
*/


public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels)
throws NullPointerException {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = Color.parseColor("#000000");
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}

Android Web View with Progress Dialog.

How to show Progress Dialog while loading a page to WebView using WebClient.
























public final class MyWebview extends Activity {

private static final int DIALOG2_KEY = 1;
private ProgressDialog pd = null;
private static final String  AmitBlog="http://amitandroid.blogspot.in/";
private WebView webView;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.help_page);
pd = new ProgressDialog(this);
webView = (WebView) findViewById(R.id.help_contents);
webView.setWebViewClient(new HelpClient());
webView.getSettings().setBuiltInZoomControls(true);

  /** Showing Dialog Here */
showDialog(DIALOG2_KEY);
}

@Override
protected void onResume() {
                super.onResume();
LoadView();
}

private void LoadView()
{
webView.loadUrl(AmitBlog);
}

 /** Its very important while navigation hardware back button if we navigate to another link .Its like a Stack pop of all the pages you visited in WebView */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (webView.canGoBack()) {
webView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}

/** WebViewClient is used to open other web link to the same Activity. */

private final class HelpClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
setTitle(view.getTitle());

   /** Dismissing Dialog Here after page load*/
dismissDialog(DIALOG2_KEY);
}

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("file")) {
return false;
} else{
view.loadUrl(url);
return true;
}
}
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id)
{
case DIALOG2_KEY:
{
pd.setMessage(getResources().getString(R.string.Loading));
pd.setIndeterminate(true);
pd.setCancelable(false);
return pd;
}
}
return null;
}
}

Click here to Download  Code

Monday 14 January 2013

Android use of external Fonts through custom views in Android

In this blog , you will find a very optimal way how to use external fonts  by using Custom view for TextView, EditText and Button.

Let us assume we have to use Custom fonts through out the application. Then its very difficult to set font to each and every view.

 Font font1 = Typeface.createFromAsset(getAssets(), "fonts/Arial.ttf");

Now we need to set this font to every widget like TextView,Button, EditText..
So explicitly we need to setFont(font1) to each view.

e.g
         TextView Title = (TextView) findViewById(R.id.title);
         TextView Summary=(TextView)findViewById(R.id.summary);
        TextView Desc = (TextView) findViewById(R.id.description);       

        Title.seFont(font1);
        Summary.setFont(font1);
        Desc.setFont(font1);

Solution:--
So to over come this issue we will create Customview for TextView. Like wise we can achieve for Button and EditText also.

Step1) Create a package for custom component.
let us suppose com.amit.customview

a) create a class name as CustomTextView and copy paste this code but make sure that the custom font should be Project Assets folder. So you can replace font name.
package com.amit.customview;

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.Button;

public class CustomTextView extends TextView{

    public CustomButton(Context context) {
        super( context );
        setFont();

    }

    public CustomTextView (Context context, AttributeSet attrs) {
        super( context, attrs );
        setFont();
    }

    public CustomTextView (Context context, AttributeSet attrs, int defStyle) {
        super( context, attrs, defStyle );
        setFont();
    }

    private void setFont() {
        Typeface normal = Typeface.createFromAsset(getContext().getAssets(),"fonts/Arial.ttf");
        setTypeface( normal, Typeface.NORMAL );

    }
}

b) Create class named as CustomEditText inside the same package and follow the same
package com.amit.customview;

import android.content.Context;
public class CustomEditText extends EditText{

    public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomEditText(Context context) {
        super(context);
        init();
    }

    private void init() {
          Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/Arial.ttf");
            setTypeface(tf);
         }

}

c) Like wise create class named as CustomButton inside the same package

package com.amit.customview;

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.Button;

public class CustomButton extends Button{

    public CustomButton(Context context) {
        super( context );
        setFont();

    }

    public CustomButton(Context context, AttributeSet attrs) {
        super( context, attrs );
        setFont();
    }

    public CustomButton(Context context, AttributeSet attrs, int defStyle) {
        super( context, attrs, defStyle );
        setFont();
    }

    private void setFont() {
        Typeface normal = Typeface.createFromAsset(getContext().getAssets(),"fonts/Arial.ttf");
        setTypeface( normal, Typeface.NORMAL );

    }
}

Step 2) Now next how to use  this CustomView inside our application
We can use it both the way either through xml layout or in Activty class.

a) First we will see how to use it from xml layout.
Now instead  of Textview we will use like this,
 <LinearLayout
        android:id="@+id/signing_details"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:orientation="vertical"
        android:weightSum="100" >

<com.amit.customview.CustomTextView
                android:id="@+id/textview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                 android:text="@string/app_name"
                 android:textSize="16sp" />
 <com.amit.customview.CustomEditText
                android:id="@+id/username"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                 android:hint="@string/userName"
                 android:textSize="16sp" />
<com.amit.customview.CustomButton
                android:id="@+id/signin"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                 android:text="@string/button"
                 android:textSize="16sp" />

</ LinearLayout>


b) Other we can use it dynamically in Activity.

        CustomTextView textView = new CustomTextView (this);
        textView.setText(res.getString(R.string.app_name));
        textView.setTextColor(Color.parseColor("#000000"));
        textView.setTextSize(16);

Like wise we can use CustomEditText and CustomButton.

Hope this help you lot..
Please fell free to give your comment to my personnel email id
amithigh.gupta@gmail.com

Android Emulator make Keyboard Support.

If you install latest Android SDK then while creating AVD you need to add keyboard Support so that keyboard can be access.

Step 1) While creating AVD ,click on new Button then select keyboard and select ok.

Step 1





Step 2) Then you will see Keyboard support in Property list of AVD. Then select Keyboard support and click the drop down and change to "Yes". Because by default it is "No".
See the below screen shots.


Now Keyboard Support is enabled to that particular AVD that you created.

Hope this will help you.. Now can get rid of touch keyboard while developing Android Application.
Like that you can Audio Recording Support, GPS Support, SD Card support etc.