Skip to main content

Featured post

Simple RecyclerView example with filter option in Android

Hi Guys, Maybe you all are expert in terms of using RecyclerView in android. This blog is simple example for using filter option with RecyclerView adapter. As for now you will instantiate RecyclerView and set the adapter to RecyclerView as following way. RecyclerView list = (RecyclerView) findViewById(R.id.list); list.setLayoutManager(new LinearLayoutManager(this)); list.setHasFixedSize(true); ArrayList&ltNumber&gt numbers = new ArrayList&lt&gt(); String ONEs[] = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN"}; String TENs[] = {"ZERO", "TEN", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY", "HUNDRED"}; String HUNDREDS[] = {"ZERO", "HUNDRED", "TWO HUND...

Set limit for fraction in decimal numbers in EditText

            Already we know that we can set which type of input the edittext should accept from user using
android:inputType="numberDecimal"


But there is no predefined function to set the limit for the edittext to How many digit it should accept after the decimal point from user. We can achieve this by using TextWatcher.


Full code example.

Following program creates a Decimal Filter.

DecimalFilter.java
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;

public class DecimalFilter implements TextWatcher {

int count= -1 ;
EditText et;
Activity activity;

public DecimalFilter(EditText edittext, Activity activity) {
et = edittext;
this.activity = activity;
}

public void afterTextChanged(Editable s) {

if (s.length() > 0) {
String str = et.getText().toString();
et.setOnKeyListener(new OnKeyListener() {

public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
count--;
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(100);//Re sets the maxLength of edittext to 100.
et.setFilters(fArray);      
}
if (count > 2) {
   Toast.makeText(activity, "Sorry! You cant enter more than two digits after decimal point!", Toast.LENGTH_SHORT).show();
}
return false;
}
});

char t = str.charAt(s.length() - 1);

if (t == '.') {
count = 0;
}

if (count >= 0) {
if (count == 2) {
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(s.length());
et.setFilters(fArray); // sets edittext's maxLength to number of digits now entered.

}
count++;
}
}

}

public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}

public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}

}


How to set filter for ourEditText using this DecimalFilter. Sample code:

MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

EditText editText1, editText2;
Button test;
Activity activity;
 
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
activity = this;
  
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
  
editText1.addTextChangedListener(new DecimalFilter(editText1, activity));
editText2.addTextChangedListener(new DecimalFilter(editText2, activity));
}

public void onCheck(View v) {
Toast.makeText(getApplication(), editText1.getText()+" and "+editText2.getText(), Toast.LENGTH_LONG).show();
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="150dp"
android:inputType="numberDecimal" >

 <requestFocus />
</EditText>

<EditText
android:id="@+id/editText2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:inputType="numberDecimal" />


<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:onClick="onCheck"
android:text="Button" />

</RelativeLayout>

screen shot of this code.



Thank You


Comments

  1. Thank you, this post was EXTREMELY helpful! I have added your class to my library. Thanks again.

    ReplyDelete
  2. I have one question. I am trying to create an additional constructor for DecimalFilter similiar to this...

    public DecimalFilter(EditText edittext, String afterTypingMessage) {
    et = edittext;
    }

    And then would like to be able to call a Toast when the user tries to type past the decimal limit. I can't seem to figure out how to do that.

    ReplyDelete
    Replies
    1. Can you show me your code where you try to call Toast message?

      Delete
  3. Well that's the thing. I don't see anywhere in your class where it triggers a spot I can call it. From what I can tell, after it reaches the decimal size limit, the class doesn't get called again. I don't fully understand the underlying methods, which is why i can't determine how/where to code a toast message for my needs.

    Where in the class does the code execute when someone tries typing in after they have reached the limit?

    ReplyDelete
    Replies
    1. See the updates friend. I have added toast message :)

      Delete
  4. Thank you for the updates. That is actually what I thought was supposed to be done as well, but the problem is, that Toast message only executes when you enter the decimal limit and also when you backspace from the limit, NOT when you try to type past the limit. From what I can tell, once you reach the limit, any other keystrokes (except the delete key) are ignored. I have set breakpoints on the entire class. When you reach the limit, and try and type, nothing in the class gets invoked, hence why I can't figure out where to put the Toast message so it works properly :(

    The idea I am going for is, that if you are typing and the characters go through, then that is fine. But if you have reached the limit, and you are typing and nothing is showing up, I want the Toast message to advise you that you have reached the limit and that is why no more characters are being entered. That way the user doesn't think the app is just broken or something. Does that make sense?

    ReplyDelete
    Replies
    1. What about this? This toast also invoked when you reach the limit only. isn't?

      Delete
    2. The toast goes off once you have typed the final digit (and if you delete the final digit). I want it to only go off when trying to type past the limit. This way, if the limit is 2 decimal places, and the user is trying to type a third digit, they won't be confused, because they will keep getting a toast saying "You can't go past 2 digits". Right now, it is confusing to the user.

      Delete
    3. See the update Brian Choan. By the way trying to toast from setOnKeyListener we will achieve it. From here the toast message will appear from you are enter the last digit.

      Delete
  5. how to achieve validation on input field if amount does not have decimal then only allow 5 digit amount but if user entered decimal then allow 8 digit in android using edittext

    ReplyDelete

Post a Comment

Popular posts from this blog

Simple example of OCRReader in Android.

Hi Friends, Maybe you all heard/used text scanning using camera feature or extracting text from Image. But this sample made it very easy for you. You can made it in very simple line of code. You can download the source code from OCRSample and import the library as a module into your project. Example usage : MainActivity.java public class MainActivity extends AppCompatActivity { private TextView textView; private final int CAMERA_SCAN_TEXT = 0; private final int LOAD_IMAGE_RESULTS = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSele...

Simple example of using Spinner in Kotlin | Android

Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Spinner in Android. In Kotlin we don't need to declare and initialize Spinner. We can simply access the id of Spinner from xml. Ex : import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Toast import android.widget.Toast.LENGTH_LONG import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //String array. val myStrings = arrayOf("One", "Two", "Three", "Four", "Five") //Adapter for spinner mySpinner.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_i...