Friday, February 10, 2017

Dialog theme transparent

Tags


1.style.xml

<style name="NewDialog">
        <item name="android:windowFrame">@null</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowTitleStyle">@null</item>
        <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
        <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
        <item name="android:backgroundDimEnabled">false</item>
        <item name="android:background">@android:color/transparent</item>
    </style>

2.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#5d9767"
    android:padding="16dp"
    android:orientation="vertical">

</LinearLayout>

3.MainActivity.java

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

public class MainActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new AlertDialog.Builder(this, R.style.NewDialog)
                .setTitle("Delete entry")
                .setMessage("Are you sure you want to delete this entry?")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // continue with delete
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // do nothing
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }
}

Customize character of EditText to image when input

Tags


This is pwd_icon.png


If image does not work properly, create an android resource directory named : drawable-xxhdpi and put your image here.

1.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#dcdcdc"
    android:padding="16dp">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/editText"
        android:inputType="text|textVisiblePassword"
        android:background="#fff"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

2.pwd_icon_padding.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/pwd_icon"
        android:bottom="5dp"/>
</layer-list>

3.MainActivity.java

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.widget.EditText;

public class MainActivity extends Activity implements TextWatcher{
    EditText editText;
    Spannable.Factory spannableFactory;
    int lastIndex = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = (EditText) findViewById(R.id.editText);
        spannableFactory = Spannable.Factory
                .getInstance();
        editText.addTextChangedListener(this);

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int count, int after) {
        if (start>4) {
            editText.removeTextChangedListener(this);
            editText.setText(getIconText(getApplicationContext(), s, start));
            editText.addTextChangedListener(this);
            editText.setSelection(s.length());
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    public Spannable getIconText(Context context, CharSequence text, int index) {
        Spannable spannable = spannableFactory.newSpannable(text);
        if (index>lastIndex) {
            spannable.setSpan(new ImageSpan(context, R.drawable.pwd_icon_padding),
                    index, index + 1,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        lastIndex=index;
        return spannable;
    }
}

Hide keyboard when touch outside EditText

You can put this up in a utility class, or if you are defining it within an activity, avoid the activity parameter, or call hideSoftKeyboard(this). The trickiest part is when to call it. You can write a method that iterates through every View in your activity, and check if it is an instanceof EditText if it is not register a setOnTouchListener to that component and everything will fall in place. In case you are wondering how to do that, it is in fact quite simple. Here is what you do, you write a recursive method like the following, in fact you can use this to do anything, like setup custom typefaces etc... Here is the method.



1.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    android:background="#cacaca"
    android:id="@+id/activity_main">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:inputType="text"
        android:background="#fff"/>
</LinearLayout>

2.MainActivity.java

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ScrollView;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setHideKeyboardOnTouch(this, findViewById(R.id.activity_main));
    }

    public static void setHideKeyboardOnTouch(final Context context, View view) {
        //Set up touch listener for non-text box views to hide keyboard.
        try {
            //Set up touch listener for non-text box views to hide keyboard.
            if (!(view instanceof EditText || view instanceof ScrollView)) {

                view.setOnTouchListener(new View.OnTouchListener() {

                    public boolean onTouch(View v, MotionEvent event) {
                        InputMethodManager in = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                        in.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                        return false;
                    }

                });
            }
            //If a layout container, iterate over children and seed recursion.
            if (view instanceof ViewGroup) {

                for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

                    View innerView = ((ViewGroup) view).getChildAt(i);

                    setHideKeyboardOnTouch(context, innerView);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

Wednesday, February 1, 2017

Get resource id by resource name

Tags
Example you have a picture name pic1.jpg in drawalbe folder. You can access your picture by use resource id R.drawable.pic1.
But if you want to access resource id by known the resource name, you can create custom method to access the resource id.


1.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="300dp" />
</LinearLayout>

2.MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.text.Spannable;
import android.widget.ImageView;
import java.lang.reflect.Field;

public class MainActivity extends Activity {
    Spannable.Factory spannableFactory;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imageView = (ImageView) findViewById(R.id.imageView);
        imageView.setBackgroundResource(getResId("pic1", R.drawable.class));
    }

    private int getResId(String resName, Class<?> c) {
        try {
            Field idField = c.getDeclaredField(resName);
            return idField.getInt(idField);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
}

Textview selector text color

Creating text selector for TextView to change text color when users presse or click on TextView.


1.text_selector.xml

Create and XML named text_selector.xml in drawable folder.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#00598f"/>
    <item android:state_activated="true" android:color="#00598f"/>
    <item android:color="#b35411" />
</selector>

2.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="50dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="49.5dp"
        android:text="Text Selector"
        android:textSize="35sp"
        android:textStyle="bold"
        android:clickable="true"
        android:gravity="center"
        android:textColor="@drawable/text_selector"/>
</LinearLayout>

Creating Dash line using XML

Tags
Create xml in drawable folder named dash_line.xml and then in the layout just define a view with background as dash_line.


1.dash_horizontal_line.xml

Create an xml in drawable folder named dash_horizontal_line.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <stroke
        android:color="#263238"
        android:dashWidth="2dp"
        android:dashGap="3dp"
        android:width="1dp"/>
</shape>

2.dash_virtical_line.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:left="-300dp"
        android:right="-300dp">
        <rotate
            android:drawable="@drawable/dash_horizontal_line"
            android:fromDegrees="90"
            android:toDegrees="90"
            android:visible="true"/>
    </item>
</layer-list>

3.activity_main.xml

Note to include android:layerType="software" or include android:hardwareAccelerated="false" to activity in AndroidManifest.xml, otherwise it won't work.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="50dp">
    <View
        android:layout_width="wrap_content"
        android:layout_height="2dp"
        android:layout_marginBottom="15dp"
        android:layout_marginTop="28dp"
        android:background="@drawable/dash_horizontal_line"
        android:layerType="software" />
</LinearLayout>

Expandable Textview

ExpandableTextView is a TextView which can expand/collapse just like the Google Play's app description. Feel free to use it all you want in your Android apps.


1.attrs.xml

Add attribute to attrs.xml in values folder.
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ExpandableTextView">
        <attr name="trimLength" format="integer"/>
    </declare-styleable>
</resources>

2.ExpandableTextView.java

package com.myapplication;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.SpannableStringBuilder;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

public class ExpandableTextView extends TextView {
    private static final int DEFAULT_TRIM_LENGTH = 50;
    private static final String ELLIPSIS = " ...";
    private CharSequence originalText;
    private CharSequence trimmedText;
    private BufferType bufferType;
    private boolean trim = true;
    private int trimLength;

    public ExpandableTextView(Context context) {
        this(context, null);
    }

    public ExpandableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandableTextView);
        this.trimLength = typedArray.getInt(R.styleable.ExpandableTextView_trimLength, DEFAULT_TRIM_LENGTH);
        typedArray.recycle();

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                trim = !trim;
                setText();
                requestFocusFromTouch();
            }
        });
    }

    private void setText() {
        super.setText(getDisplayableText(), bufferType);
    }

    private CharSequence getDisplayableText() {
        return trim ? trimmedText : originalText;
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        originalText = text;
        trimmedText = getTrimmedText(text);
        bufferType = type;
        setText();
    }

    private CharSequence getTrimmedText(CharSequence text) {
        if (originalText != null && originalText.length() > trimLength) {
            return new SpannableStringBuilder(originalText, 0, trimLength + 1).append(ELLIPSIS);
        } else {
            return originalText;
        }
    }

    public CharSequence getOriginalText() {
        return originalText;
    }

    public void setTrimLength(int trimLength) {
        this.trimLength = trimLength;
        trimmedText = getTrimmedText(originalText);
        setText();
    }

    public int getTrimLength() {
        return trimLength;
    }
}

3.activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal">

    <com.myapplication.ExpandableTextView
        android:id="@+id/text"
        android:layout_width="200dp"
        android:layout_height="wrap_content" />
</LinearLayout>

4.MainActivity.java

public class MainActivity extends Activity {
    Spannable.Factory spannableFactory;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        spannableFactory = Spannable.Factory
                .getInstance();

        String text = "ExpandableTextView is a TextView which can expand/collapse " +
                "just like the Google Play's app description. Feel free to use it all you want in your Android apps.";
        final ExpandableTextView textView = (ExpandableTextView) findViewById(R.id.text);
        textView.setText(text);
    }
}