Friday, February 10, 2017

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;
    }
}


EmoticonEmoticon