Set Minimum & Maximum value in EditText (Android).

Here is best example for set min/max value for EditText.

 
MinMaxFilter.java class file.

import android.text.InputFilter;
import android.text.Spanned;

/**
 * Created by npatel on 4/5/2016.
 */
public class MinMaxFilter implements InputFilter {

    private int mIntMin, mIntMax;

    public MinMaxFilter(int minValue, int maxValue) {
        this.mIntMin = minValue;
        this.mIntMax = maxValue;
    }

    public MinMaxFilter(String minValue, String maxValue) {
        this.mIntMin = Integer.parseInt(minValue);
        this.mIntMax = Integer.parseInt(maxValue);
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
            int input = Integer.parseInt(dest.toString() + source.toString());
            if (isInRange(mIntMin, mIntMax, input))
                return null;
        } catch (NumberFormatException nfe) { }
        return "";
    }

    private boolean isInRange(int a, int b, int c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }
}

Layout file code.

<EditText
    android:id="@+id/edittext"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Enter number"
    android:inputType="number" />

How to use this class for EditText.

EditText myEditText = (EditText)findViewById(R.id.edittext);
myEditText.setFilters(new InputFilter[]{ new MinMaxFilter("1", "30")});

Now EditText will allow only value from 1 to 30.

Send data from javascript to Native Android app.

Hello, here is sample code about how to send data from HTML/Javascript to native Android app using webview.

webview.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">

    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

 

mypage.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta
        name="viewport"
        content="width=device-width; user-scalable=0;" />
    <title>HTML Android</title>
</head>
<body>
    <h1>HTML Android</h1>
    <input
        type="button"
        value="Button 1"
        onClick="sendDataToAndroid('Button 1 is click')" />

    <input
        type="button"
        value="Button 2"
        onClick="sendDataToAndroid('Button 2 is click')" />

    function sendDataToAndroid(toast) {
        MyFunction.onButtonClick(toast);
    }
</body>
</html>

WebViewActivity.java

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;

@SuppressLint({"NewApi", "SetJavaScriptEnabled"})
public class WebViewActivity extends Activity {

    WebView mWebViewDemo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);
        mWebViewDemo = (WebView) findViewById(R.id.webview);
        ButtonClickJavascriptInterface myJavaScriptInterface = new ButtonClickJavascriptInterface(WebViewActivity.this);
        mWebViewDemo.addJavascriptInterface(myJavaScriptInterface, "MyFunction");
        mWebViewDemo.getSettings().setJavaScriptEnabled(true);
        mWebViewDemo.loadUrl("file:///android_asset/mypage.html");

    }

    public class ButtonClickJavascriptInterface {
        Context mContext;
        ButtonClickJavascriptInterface(Context c) {
            mContext = c;
        }

        @JavascriptInterface
        public void onButtonClick(String toast) {
            Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
        }
    }

}

Share link on facebook using intent in android.

Hello, friends.

After lots of research I found below code for share link on facebook using intent.

If facebook application is installed in device then Facebook will be open otherwise Facebook will open in browser.

Sample Code:

String urlToShare = "https://play.google.com/store/apps/details?id=com.facebook.katana&hl=en";
try {
    Intent mIntentFacebook = new Intent();
    mIntentFacebook.setClassName("com.facebook.katana", "com.facebook.composer.shareintent.ImplicitShareIntentHandlerDefaultAlias");
    mIntentFacebook.setAction("android.intent.action.SEND");
    mIntentFacebook.setType("text/plain");
    mIntentFacebook.putExtra("android.intent.extra.TEXT", urlToShare);
    startActivity(mIntentFacebook);
} catch (Exception e) {
    e.printStackTrace();
    Intent mIntentFacebookBrowser = new Intent(Intent.ACTION_SEND);
    String mStringURL = "https://www.facebook.com/sharer/sharer.php?u=" + urlToShare;
    mIntentFacebookBrowser = new Intent(Intent.ACTION_VIEW, Uri.parse(mStringURL));
    startActivity(mIntentFacebookBrowser);
}

Note: Only text share on facebook using intent is not possible. You must have to use Facebook SDK for share text.

Multi-Touch pinch zoom ImageView example in Android

Hello, Friends

Here is best code for Multi-Touch Pinch Zoom on ImagView.

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;

@SuppressLint("ClickableViewAccessibility")
public class PinchTouchImageView extends ImageView {

    Matrix mMatrix;

// We can be in one of these 3 states
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int MODE = NONE;

// Remember some things for zooming
    PointF mPointLast = new PointF();
    PointF mPointStatr = new PointF();
    float minScale = 1f;
    float maxScale = 3f;
    float[] mat;
    int mViewWidth, mViewHeight;
    static final int CLICK = 3;
    float mSaveScale = 1f;
    protected float mOrigWidth, mOrigHeight;
    int oldMeasuredWidth, oldMeasuredHeight;
    ScaleGestureDetector mScaleDetector;
    Context mContext;

    public PinchTouchImageView(Context context) {
        super(context);
        sharedConstructing(context);
    }

    public PinchTouchImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        sharedConstructing(context);
    }

    private void sharedConstructing(Context context) {
        super.setClickable(true);
        this.mContext = context;
        mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
        mMatrix = new Matrix();
        mat = new float[9];
        setImageMatrix(mMatrix);
        setScaleType(ScaleType.MATRIX);
        setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                mScaleDetector.onTouchEvent(event);
                PointF mCurrentPoint = new PointF(event.getX(), event.getY());
                switch (event.getAction()) {

                    case MotionEvent.ACTION_DOWN:
                        mPointLast.set(mCurrentPoint);
                        mPointStatr.set(mPointLast);
                        MODE = DRAG;
                        break;

                    case MotionEvent.ACTION_MOVE:
                        if (MODE == DRAG) {
                            float deltaX = mCurrentPoint.x - mPointLast.x;
                            float deltaY = mCurrentPoint.y - mPointLast.y;
                            float fixTransX = getFixDragTrans(deltaX, mViewWidth, mOrigWidth * mSaveScale);
                            float fixTransY = getFixDragTrans(deltaY, mViewHeight, mOrigHeight * mSaveScale);
                            mMatrix.postTranslate(fixTransX, fixTransY);
                            fixTrans();
                            mPointLast.set(mCurrentPoint.x, mCurrentPoint.y);
                        }
                        break;

                    case MotionEvent.ACTION_UP:
                        MODE = NONE;
                        int xDiff = (int) Math.abs(mCurrentPoint.x - mPointStatr.x);
                        int yDiff = (int) Math.abs(mCurrentPoint.y - mPointStatr.y);
                        if (xDiff < CLICK && yDiff < CLICK)
                            performClick();
                        break;

                    case MotionEvent.ACTION_POINTER_UP:
                        MODE = NONE;
                        break;

                }
                setImageMatrix(mMatrix);
                invalidate();
                return true; // indicate event was handled
            }
        });

    }

    public void setMaxZoom(float x) {
        maxScale = x;
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            MODE = ZOOM;
            return true;
        }
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            float mScaleFactor = detector.getScaleFactor();
            float origScale = mSaveScale;
            mSaveScale *= mScaleFactor;
            if (mSaveScale > maxScale) {
                mSaveScale = maxScale;
                mScaleFactor = maxScale / origScale;
            } else if (mSaveScale < minScale) {
                mSaveScale = minScale;
                mScaleFactor = minScale / origScale;
            }

            if (mOrigWidth * mSaveScale <= mViewWidth || mOrigHeight * mSaveScale <= mViewHeight)
                mMatrix.postScale(mScaleFactor, mScaleFactor, mViewWidth / 2, mViewHeight / 2);
            else
                mMatrix.postScale(mScaleFactor, mScaleFactor, detector.getFocusX(), detector.getFocusY());

            fixTrans();
            return true;
        }
    }

    void fixTrans() {
        mMatrix.getValues(mat);
        float transX = mat[Matrix.MTRANS_X];
        float transY = mat[Matrix.MTRANS_Y];
        float fixTransX = getFixTrans(transX, mViewWidth, mOrigWidth * mSaveScale);
        float fixTransY = getFixTrans(transY, mViewHeight, mOrigHeight * mSaveScale);
        if (fixTransX != 0 || fixTransY != 0)
            mMatrix.postTranslate(fixTransX, fixTransY);
    }

    float getFixTrans(float trans, float viewSize, float contentSize) {
        float minTrans, maxTrans;
        if (contentSize <= viewSize) {
            minTrans = 0;
            maxTrans = viewSize - contentSize;
        } else {
            minTrans = viewSize - contentSize;
            maxTrans = 0;
        }

        if (trans < minTrans)
            return -trans + minTrans;
        if (trans > maxTrans)
            return -trans + maxTrans;

        return 0;

    }

    float getFixDragTrans(float delta, float viewSize, float contentSize) {
        if (contentSize <= viewSize) {
            return 0;
        }
        return delta;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mViewWidth = MeasureSpec.getSize(widthMeasureSpec);
        mViewHeight = MeasureSpec.getSize(heightMeasureSpec);
        if (oldMeasuredHeight == mViewWidth && oldMeasuredHeight == mViewHeight || mViewWidth == 0 || mViewHeight == 0)
            return;
        oldMeasuredHeight = mViewHeight;
        oldMeasuredWidth = mViewWidth;
        if (mSaveScale == 1) {
        // Fit to screen.
            float scale;
            Drawable mDrawable = getDrawable();
            if (mDrawable == null || mDrawable.getIntrinsicWidth() == 0 || mDrawable.getIntrinsicHeight() == 0)
                return;
            int bmWidth = mDrawable.getIntrinsicWidth();
            int bmHeight = mDrawable.getIntrinsicHeight();
            float scaleX = (float) mViewWidth / (float) bmWidth;
            float scaleY = (float) mViewHeight / (float) bmHeight;
            scale = Math.min(scaleX, scaleY);
            mMatrix.setScale(scale, scale);
            // Center the image
            float redundantYSpace = (float) mViewHeight - (scale * (float) bmHeight);
            float redundantXSpace = (float) mViewWidth - (scale * (float) bmWidth);
            redundantYSpace /= (float) 2;
            redundantXSpace /= (float) 2;
            mMatrix.postTranslate(redundantXSpace, redundantYSpace);
            mOrigWidth = mViewWidth - 2 * redundantXSpace;
            mOrigHeight = mViewHeight - 2 * redundantYSpace;
            setImageMatrix(mMatrix);
        }
        fixTrans();
    }

}

 

Circular ImageView example in Android.

Hello, Friends

Here is full code for Circular ImageView example.

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CircularImageView">
        <attr name="border" format="boolean"></attr>
        <attr name="border_width" format="dimension"></attr>
        <attr name="border_color" format="color"></attr>
        <attr name="shadow" format="boolean"></attr>
    </declare-styleable>

    <declare-styleable name="Theme">
        <attr name="circularImageViewStyle" format="reference"></attr>
    </declare-styleable>
</resources>

 

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.pickimagedemo.android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <com.pickimagedemo.android.CircularImageView
        android:id="@+id/view_image_imageview_image"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:contentDescription="@string/app_name"
        android:scaleType="fitXY"
        android:src="@drawable/ic_launcher"
        app:border="true"
        app:shadow="true" />

    <com.pickimagedemo.android.CircularImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:contentDescription="@string/app_name"
        android:scaleType="fitXY"
        android:src="@drawable/ic_launcher"
        app:border="true"
        app:border_color="#FF00FF"
        app:border_width="2dp"
        app:shadow="true" />

    <com.pickimagedemo.android.CircularImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:contentDescription="@string/app_name"
        android:scaleType="fitXY"
        android:src="@drawable/ic_launcher"
        app:border="true"
        app:border_color="#303030"
        app:border_width="3dp"
        app:shadow="true" />

</LinearLayout>

 

CircularImageView.java

import android.annotation.SuppressLint;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

@SuppressLint({"NewApi", "DrawAllocation"})
public class CircularImageView extends ImageView {

    private int mBorderWidth;
    private int mCanvasSize;
    private Bitmap mBitmap;
    private Paint mPaint;
    private Paint mPaintBorder;

    public CircularImageView(final Context context) {
        this(context, null);
    }

    public CircularImageView(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.circularImageViewStyle);
    }

    @SuppressLint("Recycle")
    @SuppressWarnings("static-access")
    public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        // init paint
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaintBorder = new Paint();
        mPaintBorder.setAntiAlias(true);
        mPaintBorder.setStyle(Style.STROKE.STROKE);

        // load the styled attributes and set their properties
        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView, defStyle, 0);
        if (attributes.getBoolean(R.styleable.CircularImageView_border, true)) {
            int defaultBorderSize = (int) (4 * getContext().getResources().getDisplayMetrics().density + 0.5f);
            setBorderWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_border_width, defaultBorderSize));
            setBorderColor(attributes.getColor(R.styleable.CircularImageView_border_color, Color.WHITE));
        }

        if (attributes.getBoolean(R.styleable.CircularImageView_shadow, false))
            addShadow();

    }

    public void setBorderWidth(int borderWidth) {
        mPaintBorder.setStrokeWidth(borderWidth);
        this.mBorderWidth = borderWidth;
        this.requestLayout();
        this.invalidate();

    }

    public void setBorderColor(int borderColor) {
        if (mPaintBorder != null)
            mPaintBorder.setColor(borderColor);
        this.invalidate();

    }

    public void addShadow() {
        setLayerType(LAYER_TYPE_SOFTWARE, mPaintBorder);
    }

    @SuppressLint("DrawAllocation")
    @Override
    public void onDraw(Canvas canvas) {
        mBitmap = drawableToBitmap(getDrawable());
        if (mBitmap != null) {
            mCanvasSize = canvas.getWidth();
            if (canvas.getHeight() < mCanvasSize)
                mCanvasSize = canvas.getHeight();
            BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(
                    mBitmap, mCanvasSize, mCanvasSize, false),
                    Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            mPaint.setShader(shader);

            int circleCenter = (mCanvasSize - (mBorderWidth * 2)) / 2;
            canvas.drawCircle(circleCenter + mBorderWidth, circleCenter
                    + mBorderWidth, ((mCanvasSize - (mBorderWidth * 2)) / 2)
                    + mBorderWidth - 4.0f, mPaintBorder);
            canvas.drawCircle(circleCenter + mBorderWidth, circleCenter
                            + mBorderWidth,
                    ((mCanvasSize - (mBorderWidth * 2)) / 2) - 4.0f, mPaint);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int mWidth = measureWidth(widthMeasureSpec);
        int mHeight = measureHeight(heightMeasureSpec);
        setMeasuredDimension(mWidth, mHeight);
    }

    private int measureWidth(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if (specMode == MeasureSpec.EXACTLY) {
            // The parent has determined an exact size for the child.
            result = specSize;
        } else if (specMode == MeasureSpec.AT_MOST) {
            // The child can be as large as it wants up to the specified size.
            result = specSize;
        } else {
            // The parent has not imposed any constraint on the child.
            result = mCanvasSize;
        }
        return result;
    }

    private int measureHeight(int measureSpecHeight) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpecHeight);
        int specSize = MeasureSpec.getSize(measureSpecHeight);
        if (specMode == MeasureSpec.EXACTLY) {
            // We were told how big to be
            result = specSize;
        } else if (specMode == MeasureSpec.AT_MOST) {
            // The child can be as large as it wants up to the specified size.
            result = specSize;
        } else {
            // Measure the text (beware: ascent is a negative number)
            result = mCanvasSize;
        }
        return (result + 2);
    }

    public Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable == null) {
            return null;
        } else if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return bitmap;
    }
}