How to apply InputFilter to EditTextPreferences? - android

I want to apply InputFilter to my EditTextPreferences...
Before I used the PreferenceActivity I had EditTexts with Filters like that:
et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.ETminsim);
et3 = (EditText) findViewById(R.id.ETdelay);
et1.setText(Integer.toString(PlotView.playlist_size), EditText.BufferType.EDITABLE);
et2.setText(Integer.toString(conversorToInt(PlotView.min_sim)), EditText.BufferType.EDITABLE);
et3.setText(Integer.toString(MusicService.getSeek()/1000), EditText.BufferType.EDITABLE);
et1.setFilters(new InputFilter[]{ new InputFilterMinMax(1, 30)});
et2.setFilters(new InputFilter[]{ new InputFilterMinMax(0, 100)});
et3.setFilters(new InputFilter[]{ new InputFilterMinMax(0, 300)});
But how can I reference to the EditTexts of the EditTextPreference in order to set these Filters?
My new Code:
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
getPreferenceManager().setSharedPreferencesName(Singleton.PREFS_NAME);
addPreferencesFromResource(R.xml.prefs);
//TODO set InputFilter
}

Konstantin had it mostly correct. Combine his answer with Sebastian's comment on his answer and you get
EditText editText1 = ((EditTextPreference) findPreference(preference_1_key))
.getEditText();
editText1.setFilters(new InputFilter[]{ new InputFilterMinMax(1, 30) });

Assuming this is your preference Activity and you can get the items by id:
EditTextPreference editTextPreference = findByViewId(R.id.editPref1);
EditText editText = editTextPreference.getEditText();
editText.setFilters(................);

This has more flexibility.
public class Utility {
public static void setEditTextInputFilter(EditText editText, final String blockCharacterSet) {
InputFilter filter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source != null && blockCharacterSet.contains(("" + source))) {
return "";
}
return null;
}
};
editText.setFilters(new InputFilter[]{filter});
}
}
How to use:
exampleEditText is the editText which want to block input "-".
Utility.setEditTextInputFilter(exampleEditText, "-");

Related

check that all edittext is filled and display alert message

I have 9 edittext. Each edittext is in the form of a square. I look if all edittext has values, then an alert message is displayed without click of any button.
I tried with this code but it does not run.
Any help would be appreciated.
public int Summ(int x, int y, int z) {
int sum = 0;
sum = x + y + z;
return sum;
}
private void alertDialogLost()
{
int a= Integer.parseInt(et1.getText().toString());
int b = Integer.parseInt(et2.getText().toString());
int c = Integer.parseInt(et3.getText().toString());
int d = Integer.parseInt(et4.getText().toString());
int e = Integer.parseInt(et5.getText().toString());
int f = Integer.parseInt(et6.getText().toString());
int g = Integer.parseInt(et7.getText().toString());
int h = Integer.parseInt(et8.getText().toString());
int k = Integer.parseInt(et9.getText().toString());
if ((Summ(a,b,c)== Solution)&&(Summ(d,e,f)== Solution)&&(Summ(g,h,k)==Solution)&&
(Summ(a,d,g)==Solution)&&(Summ(b,e,h)== Solution)&&(Summ(c,f,k)==Solution)
&&(Summ(a,e,k)==Solution)&&(Summ(c,e,g)==Solution))
{
AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
View view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.alertdiag, null);
TextView title = (TextView) view1.findViewById(R.id.title);
TextView message = (TextView) view1.findViewById(R.id.message);
ImageView icone = (ImageView) view1.findViewById(R.id.icone);
title.setText("Result");
icone.setImageResource(R.drawable.smilega);
message.setText("you have winner");
builder1.setPositiveButton("contenue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
finish();
}
});
builder1.setView(view1);
builder1.setCancelable(false);
AlertDialog alertDialog1 = builder1.create();
alertDialog1.show();
}
}
If you just want to show an AlertDialog the moment all nine EditText fields have values in them, using a TextWatcher would probably do the trick.
First, let's start with making things easier on ourselves. We'll add each EditText to an ArrayList, so we can iterate through them with a forEach loop:
List<EditText> editTextArrayList= new ArrayList<>();;
editTextArrayList.add(et1);
editTextArrayList.add(et2);
editTextArrayList.add(et3);
editTextArrayList.add(et4);
editTextArrayList.add(et5);
editTextArrayList.add(et6);
editTextArrayList.add(et7);
editTextArrayList.add(et8);
editTextArrayList.add(et9);
Then, let's set up a method to iterate through all nine EditText fields, checking if each one has a value. If any of them do not, the AlertDialog will not show:
private void checkAllEditTexts() {
boolean allFilled = true;
for (EditText editText : editTextArrayList) {
if (editText.getText().toString().isEmpty()) {
allFilled = false;
break;
}
}
if (allFilled) {
// show your AlertDialog
}
}
Then we set up our TextWatcher, which will call the checkAllEditTexts() method if any text is changed on the EditText fields we'll be assigning it to:
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
checkAllEditTexts();
}
};
And finally, just below where we added the EditText fields to the ArrayList, we set up a forEach loop to add the TextWatcher:
List<EditText> editTextArrayList= new ArrayList<>();;
editTextArrayList.add(et1);
editTextArrayList.add(et2);
editTextArrayList.add(et3);
editTextArrayList.add(et4);
editTextArrayList.add(et5);
editTextArrayList.add(et6);
editTextArrayList.add(et7);
editTextArrayList.add(et8);
editTextArrayList.add(et9);
for (EditText editText : editTextArrayList) {
editText.addTextChangedListener(textWatcher);
}
...and that should display your AlertDialog as soon as all nine text fields have a value.

EditText not adding space after word swiped in

I have an android phone using googles keyboard. On any EditText field in any other app if I use the swipe method to enter text in, it adds a space after each word. However, I have written my own app and when I use the swipe method to enter text on my EditText field it does NOT add a space sothewordsbleedtogether. This is very annoying.
I have an AlertDialog with a linear view added. On that linear view there is a text EditText. Here is my code to create the EditText and add it to the view:
final EditText titleBox = new EditText(this);
titleBox.setInputType(InputType.TYPE_TEXT_FLAG_AUTO_CORRECT |
InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES |
InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
titleBox.setHint("Title");
layout.addView(titleBox);
Any ideas why its not adding spaces in between my words?
This was marked as a possible duplicate, but that question was about not allowing the first character to be a space....Im asking about allowing a space after words that are entered via a keyboard swipe.
Update
Here is the entire method of similar page, its having the same issue, its slightly less complex then the initial page I was troubleshooting. This one doesn't even have a LinearLayout associated:
private void addBudget(final Budget budget) {
EditText taskEditText = new EditText(this);
taskEditText.setId(R.id.add_budget_text);
taskEditText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
String dialogTitle = "Add budget";
final AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(dialogTitle)
.setMessage("What do you want to call this budget?")
.setView(taskEditText)
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// final String task = ;
SQLiteDatabase db = mHelper.getWritableDatabase();
Budget lBudget = new Budget();
if (budget != null) {
lBudget = budget;
}
EditText taskEditText = (EditText) findViewById(R.id.add_budget_text);
lBudget.title = String.valueOf(taskEditText.getText());
// Init custom budget object //new Budget(){{ title=task; id = budgetID;}}
int retId = mHelper.saveBudget(db, lBudget);
db.close();
int retRow = updateUI(retId);
mTaskListView.smoothScrollToPosition(retRow);
}
})
.setNegativeButton("Cancel", null)
.create();
// Handle done on soft keyboard
taskEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
int result = actionId & EditorInfo.IME_MASK_ACTION;
if (result == EditorInfo.IME_ACTION_DONE) {
dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
return true;
}
return false;
}
});
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
}
I didnt know if you got solved, i just had the same problem today and found a way to solve it.
I saw a "extrange" performance of the swipe, sometimes it showed the "blankspace" and sometimes not.
The way i found to check if it was shown and if it didnt, add it, was this:
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
checkCancel();
int compare = count-before;
if(compare>1){
String text = editText.getText().toString();
String lastChar = (text.substring(text.length()-1,text.length()));
if(!lastChar.equals(" ")){
String plus = text+" ";
editText.setText(plus);
editText.setSelection(editText.getText().length());
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
} );
You can see, onTextChanged can use the variables "before" and "count" and if the compare (difference between last word and current one) is more than 1, it's a word entered by Swipe. Then you can check if the "blankspace" is shown, and if not, just add it and perfom anything you want with it.
Hope it helps!
Could you try this? Add the filter into the editText. I used it for enter code on my app.
EditText et = (EditText) findViewById(R.id.edit_text);
et.setFilters(new InputFilter[] {
new InputFilter() {
#Override
public CharSequence filter(CharSequence charSequence, int start, int end, Spanned spanned, int start, int end {
if(charSequence.equals("")){
return charSequence;
}
if(charSequence.toString().matches("[a-zA-Z ]+")){
return charSequence;
}
return "";
}
}
});
So I uninstalled the google keyboard and reinstalled and I changed the build to release. One of those two things fixed it.

filter method is called twice android edittext on change keyboard language

I like to convert on the fly letters from cyrillic to latin. For example when user enter cyrillic letter I like to convert letter to latin. Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test = (EditText) findViewById(R.id.test);
InputFilter filter = new InputFilter() {
TransliterationHelper tr = new TransliterationHelper();
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (tr.isAlphaCyrilic(source.toString())) {
String convertedString = tr.returnLatinForCyrilic(source.toString());
return convertedString.toUpperCase();
} else if (tr.isAlpha(source.toString()))
return source.toString().toUpperCase();
else
return "";
return null;
}
};
test.setFilters(new InputFilter[]{filter});
}
Here is isAlphaCyrilic function:
public static boolean isAlphaCyrilic(String s) {
boolean isCyrilic = false;
for (char c : s.toCharArray()) {
if (Character.UnicodeBlock.of(c) == Character.UnicodeBlock.CYRILLIC) {
isCyrilic = true;
break;
}
}
return isCyrilic;
}
Here is the code for isAlpha
public static boolean isAlpha(String s) {
String pattern = "^[a-zA-Z ]*$";
if (s.matches(pattern)) {
return true;
}
return false;
}
The function returnLatinForCyrilic, return matched character for cyrillic letter:
public String returnLatinForCyrilic(String s) {
String strTranslated = cyrilicToLatinMap.get(s);
return strTranslated;
}
For example I enter only latin letters or cyrillic letters everything works ok, but when I enter cyrillic letter after latin (I changed keyboard language) method filter called again, and I don't like that.
Does someone has some idea?
I put android:inputType="textNoSuggestions"
so the method filter was not called twice.

How to exclude the digit number in the android reg expression

I am working to validate the name field, since there are so many country using different symbol as first, last name, I am going to validate the field by checking whether there is a number among the characters
private static final String NAME_REGEX = "\\d*";
public static boolean isName(EditText editText) {
return isValid(editText, NAME_REGEX) ? false : true; //Match digit pattern return true , meaning it is not a valid name
}
public static boolean isValid(EditText editText, String regex) {
String text = editText.getText().toString().trim();
return Pattern.matches(regex, text) ? true : false;
}
However, this pattern seems not working as I add some number it is still valid , what is the correct way of implement this? Thanks a lot
Just do this
private static final String NAME_REGEX = ".*\\d.";
I think this will work.
Do not use regx. InputFilter is proper way to do this kind of validation.
public class MainActivity extends Activity {
EditText edit;
InputFilter filter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source.length() > 0) {
if (Character.isDigit(source.charAt(0)))
return "";
}
return null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.edit);
edit.setFilters(new InputFilter[] { filter });
}
}
If you set the EditText to inputType to "textPersonName" there is no need for validation.
android:inputType="textPersonName"

Android EditText setError() doesn't work as expected

I am having a problem with setError() on EditText. When an activity is opened, it checks if certain fields are empty and sets error message on them if true. However, the exclamation mark icon is only displayed in case I write some text in field and then delete it. If I lose focus on that field, the icon will disappear again. Both fields Naam and Telefonnumer have this validation.
I use Android 2.2.2 SDK and the application is run on Nexus 7 with latest updates.
I have Util class:
public class Util {
private static String TAG = "Util Class";
public static boolean editTextIsEmpty(EditText edittext) {
if (edittext.getText().toString().trim().length() < 1)
return true;
else
return false;
}
public void editTextListener(final EditText editText) {
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (editTextIsEmpty(editText) && editText.isEnabled())
editText.setError("Nodig");
else
editText.setError(null);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (editTextIsEmpty(editText) && editText.isEnabled())
editText.setError("Nodig");
else
editText.setError(null);
}
});
}
}
and then I have method validateInput() in my activity:
public class DeliveryActivity extends BaseActivity {
private ImageButton btnSetDate;
private Button btnToSummary;
private Button btnSearchAddress;
private EditText txtPostcode;
private EditText txtHouseNumber;
private EditText txtHouseNumberSuffix;
private EditText txtStreet;
private EditText txtCity;
private EditText txtDeliveryDate;
private EditText txtName;
private EditText txtPhone;
private EditText txtEmail;
private EditText txtRemark;
private TextView lblExtraDeliveryInfo;
private Spinner spinnerDelivery;
private Spinner spinnerDeliveryPeriod;
private Spinner spinnerContact;
private Spinner spinnerDeliveryAddress;
private Spinner spinnerExtraDeliveryInfo;
private RelativeLayout rlDeliveryAddressDetails;
private DevRestHelper additionalDeliveryInfo;
private DevRestHelper searchClientAddress;
private Util util = new Util();
private int year;
private int month;
private int day;
public static final int DIALOG_DATEPICKER = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delivery);
initControls();
validateInput();
}
private void initControls() {
btnSetDate = (ImageButton) findViewById(R.id.activity_delivery_btnCalendar);
btnToSummary = (Button) findViewById(R.id.activity_delivery_btnSummary);
btnSearchAddress = (Button) findViewById(R.id.activity_delivery_btnSearchAddress);
spinnerDelivery = (Spinner) findViewById(R.id.activity_delivery_spinnerDeliveryMethod);
spinnerDeliveryPeriod = (Spinner) findViewById(R.id.activity_delivery_spinnerDeliveryPeriod);
spinnerContact = (Spinner) findViewById(R.id.activity_delivery_spinnerContactperson);
spinnerDeliveryAddress = (Spinner) findViewById(R.id.activity_delivery_spinnerDeliveryAddress);
spinnerExtraDeliveryInfo = (Spinner) findViewById(R.id.activity_delivery_spinnerExtraDeliveryInformation);
txtPostcode = (EditText) findViewById(R.id.activity_delivery_txtPostcode);
txtHouseNumber = (EditText) findViewById(R.id.activity_delivery_txtHousenumber);
txtHouseNumberSuffix = (EditText) findViewById(R.id.activity_delivery_txtHousenumberSuffix);
txtStreet = (EditText) findViewById(R.id.activity_delivery_txtStreet);
txtCity = (EditText) findViewById(R.id.activity_delivery_txtCity);
txtDeliveryDate = (EditText) findViewById(R.id.activity_delivery_txtDeliveryDate);
txtName = (EditText) findViewById(R.id.activity_delivery_txtName);
txtPhone = (EditText) findViewById(R.id.activity_delivery_txtPhone);
txtEmail = (EditText) findViewById(R.id.activity_delivery_txtEmail);
txtRemark = (EditText) findViewById(R.id.activity_delivery_txtRemark);
lblExtraDeliveryInfo = (TextView) findViewById(R.id.activity_delivery_lblExtraDetailInformation);
rlDeliveryAddressDetails = (RelativeLayout) findViewById(R.id.activity_delivery_rlDeliveryAddressDetails);
}
private void validateInput() {
util.editTextListener(txtPostcode);
util.editTextListener(txtHouseNumber);
util.editTextListener(txtDeliveryDate);
}
}
Let me just say that code work on BlueStacks emulator.
There is a known bug with setError on Jelly Bean_MR1 (4.2 and 4.2.1). I am however assuming that the Nexus 7 you are testing with is running one of those versions of Android. See here: http://code.google.com/p/android/issues/detail?id=40417
The error will be shown while you have focus on that EditText field, but when you lose focus, the error icon is not visible to notify the user of the problem.
Before you set Error on any view or edit text, just call the
yourEditText.requestFocus();
yourEditText.setError("Your Error Message");
then set Error. it will solve your problem. Atleast mine did.
try this
new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
if (editTextIsEmpty(editText) && editText.isEnabled())
editText.setError("Nodig");
else
editText.setError(null);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// nothing here
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// nothing here
}
}
You can use following code:
May it will be helpful to you:
mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId,
com.android.internal.R.styleable.Theme_errorMessageBackground);
mView.setBackgroundResource(mPopupInlineErrorBackgroundId);
However, you can set a Spanned and a custom error icon using the overloaded setError(CharSequence, Drawable).
You can easily create a Spanned from HTML using fromHtml().
For Example:
yourEditText.setError(Html.fromHtml("<font color='blue'>this is the error</font>"));
This is the only you need to get expected setError behaviour on the TextView
android:focusable="true"
android:clickable="true"
android:focusableInTouchMode="true"

Categories

Resources