How to set the CharSequence for setError() - android

I am very new to coding. What i'm trying to do is that when someone does not write anything, use an setError() like "Please write your your answer." However, when someone click the text box, i want the writing to go away but the error symbol to stay. I have seen and tried solution where you override the setError to just set the picture.
public MyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void setError(CharSequence error, Drawable icon) {
setCompoundDrawables(null, null, icon, null);
}
However, with this method, i cannot set a charsequence

you can set error on click on the button say register or signin whatever is your function to go ahead. and check that the string is empty than
set the error like
String str = myEditText.getText().toString();
if (str.length() == 0 || str.equals("")) {
myEditText.setError("field can't be empty");
}

Simple handle in button click and show error msg like below. its work for me.
#Override
public void onClick(View v) {
String data = mEditText.getText().toString();
if(data.isEmpty())
{
mEditText.setError(""Please write your your answer.");
return;
}
}

Related

SetError on EditText

I am working on an android app. I am having an EditText on which I have applied OnCllickListener().
EditText _input = new EditText(context);
_input.setSingleLine(true);
_input.setFocusable(false);
I am setting OnClickListener() on this EditText:
_input.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// OnClick work here
}
});
I have applied some validations on this field and calling setError() method on this EditText. It shows that red icon of error in the EditTextwhen the validation fails. But when I click on that error icon it executes the OnClickListener() on this EditTextand I am not able to see the error occurred.
Is there any other way to do so, so that I can handle both functions.
Thanks a lot in advanced !!!
You would check if currently the edit text is in an error state, within the onclick handler:
_input.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view.getError() == null) {
// do not handle the click
return;
}
}
});
You can check for an error like like this:
if(view.getError() == null) return;
See the doc here
getError()
Returns the error message that was set to be displayed with
setError(CharSequence), or null if no error was set or if it the error
was cleared by the widget after user input.
Source
I have solved this with a simple solution. Just set text of editText to empty string before setting error and error message will show again like without onClickListener.

Android NumberPicker with Formatter doesn't format on first rendering

I have a NumberPicker that has a formatter that formats the displayed numbers either when the NumberPicker spins or when a value is entered manually. This works fine, but when the NumberPicker is first shown and I initialize it with setValue(0) the 0 does not get formatted (it should display as "-" instead of 0). As soon as I spin the NumberPicker from that point on everything works.
How can I force the NumberPicker to format always - Both on first rendering and also when I enter a number manually with the keyboard?
This is my formatter
public class PickerFormatter implements Formatter {
private String mSingle;
private String mMultiple;
public PickerFormatter(String single, String multiple) {
mSingle = single;
mMultiple = multiple;
}
#Override
public String format(int num) {
if (num == 0) {
return "-";
}
if (num == 1) {
return num + " " + mSingle;
}
return num + " " + mMultiple;
}
}
I add my formatter to the picker with setFormatter(), this is all I do to the picker.
picker.setMaxValue(max);
picker.setMinValue(min);
picker.setFormatter(new PickerFormatter(single, multiple));
picker.setWrapSelectorWheel(wrap);
dgel's solution doesn't work for me: when I tap on the picker, formatting disappears again. This bug is caused by input filter set on EditText inside NumberPicker when setDisplayValues isn't used. So I came up with this workaround:
Field f = NumberPicker.class.getDeclaredField("mInputText");
f.setAccessible(true);
EditText inputText = (EditText)f.get(mPicker);
inputText.setFilters(new InputFilter[0]);
I also encountered this annoying little bug. Used a technique from this answer to come up with a nasty but effective fix.
NumberPicker picker = (NumberPicker)view.findViewById(id.picker);
picker.setMinValue(1);
picker.setMaxValue(5);
picker.setWrapSelectorWheel(false);
picker.setFormatter(new NumberPicker.Formatter() {
#Override
public String format(int value) {
return my_formatter(value);
}
});
try {
Method method = picker.getClass().getDeclaredMethod("changeValueByOne", boolean.class);
method.setAccessible(true);
method.invoke(picker, true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
Calling that private changeValueByOne method immediately after instantiating my number picker seems to kick the formatter enough to behave how it should. The number picker comes up nice and clean with the first value formatted correctly. Like I said, nasty but effective.
I had the same problem and I used the setDisplayedValues() method instead.
int max = 99;
String[] values = new String[99];
values[0] = “-” + mSingle
values[1] =
for(int i=2; i<=max; i++){
makeNames[i] = String.valueOf(i) + mMultiple;
}
picker.setMinValue(0);
picker.setMaxValue(max);
picker.setDisplayedValues(values)
This doesn't allow the user to set the value manually in the picker though.
The following solution worked out for me for APIs 18-26 without using reflection, and without using setDisplayedValues().
It consists of two steps:
Make sure the first element shows by setting it's visibility to invisible (I used Layout Inspector to see the difference with when it shows, it's not logical but View.INVISIBLE actually makes the view visible).
private void initNumberPicker() {
// Inflate or create your BugFixNumberPicker class
// Do your initialization on bugFixNumberPicker...
bugFixNumberPicker.setFormatter(new NumberPicker.Formatter() {
#Override
public String format(final int value) {
// Format to your needs
return aFormatMethod(value);
}
});
// Fix for bug in Android Picker where the first element is not shown
View firstItem = bugFixNumberPicker.getChildAt(0);
if (firstItem != null) {
firstItem.setVisibility(View.INVISIBLE);
}
}
Subclass NumberPicker and make sure no click events go through so the glitch where picker elements disapear on touch can't happen.
public class BugFixNumberPicker extends NumberPicker {
public BugFixNumberPicker(Context context) {
super(context);
}
public BugFixNumberPicker(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BugFixNumberPicker(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
public boolean performClick() {
return false;
}
#Override
public boolean performLongClick() {
return false;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return false;
}
}
Here's my solution based on answers by torvin and Sebastian. You don't have to subclass anything or use reflection.
View editView = numberPicker.getChildAt(0);
if (editView instanceof EditText) {
// Remove default input filter
((EditText) editView).setFilters(new InputFilter[0]);
}
Calling the private method changeValueByOne() via reflection as described in an earlier answer works for me on API Level 16 (Android 4.1.2 and up), but it does not seem to help on API Level 15 (Android 4.0.3), however!
What works for me on API Level 15 (and up) is to use your own custom formatter to create String array and pass that with the method setDisplayedValues() to the number picker.
See also: Android 3.x and 4.x NumberPicker Example
The answer provided by NoActivity worked for me but I only had to do:
View firstItem = bugFixNumberPicker.getChildAt(0);
if (firstItem != null) {
firstItem.setVisibility(View.INVISIBLE);
}
to fix the issue. I did not need to subclass NumberPicker. I did not see the issue where picker elements disappear on touch.
Kotlin version based on Nikolai's answer
private fun initNumberPicker() {
nrPicker.children.iterator().forEach {
if (it is EditText) it.filters = arrayOfNulls(0) // remove default input filter
}
}
I managed to fix it by calling
picker.invalidate();
just after setting the formatter.
Improved Nikolai answer if selected index is not 0. Not to great for performances but fix the problem..
for(index in numberPicker.minValue..numberPicker.maxValue) {
val editView = numberPicker.getChildAt(index-numberPicker.minValue)
if (editView != null && editView is EditText) {
// Remove default input filter
(editView as EditText).filters = arrayOfNulls(0)
}
}

Android Instrumentation - Assert fails

I have a small activity that contains a textview and a password. I have written a small text to test this activity. But the assert on the last line is failing. Could someone please tell me why ?
loginScreenActivity=startActivity(mStartIntent, null, null);
assertNotNull(loginScreenActivity);
mInstrumentation.waitForIdleSync();
final EditText userName=(EditText)loginScreenActivity.findViewById(R.id.userName);
final EditText password=(EditText)loginScreenActivity.findViewById(R.id.password);
loginScreenActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
userName.requestFocus();
}
});
mInstrumentation.waitForIdleSync();
this.sendKeys(KeyEvent.KEYCODE_R);
this.sendKeys(KeyEvent.KEYCODE_SHIFT_LEFT);
this.sendKeys(KeyEvent.KEYCODE_A);
this.sendKeys(KeyEvent.KEYCODE_F);
this.sendKeys(KeyEvent.KEYCODE_A);
this.sendKeys(KeyEvent.KEYCODE_Q);
this.sendKeys(KeyEvent.KEYCODE_A);
this.sendKeys(KeyEvent.KEYCODE_T);
assertTrue(userName.getText().toString().equals("Rafaqat"));
From the sequence, I guess you are inputing "rAfarqat"?

EditText setError message does not clear after input

Ok so I only have a EditText field and a button, which when pressed triggers an AsyncTask.
EditText playerName = (EditText)findViewById(R.id.playerEditText);
if(playerName.getText().toString().length() == 0 )
playerName.setError("Player name is required!");
else {
// do async task
}
The problem is that the error message seems to stay up even after when I input valid text to search. Is there a way to remove the error as soon as the EditText is not empty?
In your else bracket, put playerName.setError(null), which will clear the error.
API documentation: "The icon and error message will be reset to null when any key events cause changes to the TextView's text."
Though it is not so - and therefore we can regard this as bug.
If you use inputType such as textNoSuggestions, textEmailAddress, textPassword, the error is unset after a character is typed. Nearly as documented but again not exactly - when you delete a character, error stays.
It seems, a simple workaround with addTextChangedListener and setError(null) can attain promised behavior.
Besides there are posts about icon losing on Android 4.2. So use with care.
Try this listener:
playerName.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable edt){
if( playerName.getText().length()>0)
{
playerName.setError(null);
}
}
If you want to hide the error message one way is you apply onclicklistener on the edit box and then
editTextName.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editTextName.setError(Null)
}
});
Below code worked for me
#OnTextChanged(
value = R.id.editTextName,
callback = OnTextChanged.Callback.TEXT_CHANGED)
public void afterInput(CharSequence sequence) {
editTextName.setError(null);
editTextName.setErrorEnabled(false);
}
'
editTextName.setError(null) Will clear the error message.
editTextName.setErrorEnabled(false) Will remove additional padding.
Add a TextWatcher to your EditText and onError, show your error message using et.setError(errorMessage) else you can remove the error message and error icon like below.
// to remove the error message in your EditText
et.setError(null);
// to remove the error icon from EditText.
et.setCompoundDrawables(null, null, null, null);
This code worked for me.
textInputSetting(binding.emailEdt)
fun textInputSetting(view: TextInputLayout) {
view.apply {
this.editText!!.addTextChangedListener {
if (this.editText!!.text.isNotEmpty()) {
this.error = null
this.isErrorEnabled = false
}
}
}
}

Anybody know how to select text in webview in android? not use emulateShiftHeld,since the docs said " This method is deprecated"

I try to select text in webview, after I select text,I need to decide what to do next.not just copy the selected text.I have more choice for user to choose from.I mean, after user selected text in webview,could I prompt out a some button for further? I tried use emulateshiftheld to solve my problem.but google's docs said " This method is deprecated".
also,I can't prompt out some choice button.
you can clck the link to see what I mean. link: https://public.blu.livefilestore.com/y1pHhMR2iyIbQN7uJ2C-9CLLJBosWAZw2r4MvD0qyyTG-QWUM-06i6HFu4Fn4oaWnHMbDyTBOa-CPwN6PwoZNifSQ/select.jpg?download&psid=1
Pasting relevant code from WebView emulateShiftHeld() on Android Newer SDK's
/**
* Select Text in the webview and automatically sends the selected text to the clipboard
*/
public void selectAndCopyText() {
try {
KeyEvent shiftPressEvent = new KeyEvent(0,0,KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_SHIFT_LEFT,0,0);
shiftPressEvent.dispatch(mWebView);
} catch (Exception e) {
throw new AssertionError(e);
}
}
The question is very old, but for other people here is a solution with javascript for API 19+. Just add this to your WebView:
public void getSelectedText(final SelectedTextInterface selectedTextInterface) {
evaluateJavascript("(function(){return window.getSelection().toString()})()", new ValueCallback<String>() {
#Override
public void onReceiveValue(final String selectedText) {
if (selectedText != null && !selectedText.equals("")) {
//If you don't have a context, just call
//selectedTextInterface.onTextSelected(selectedText);
if (context instanceof Activity) {
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
selectedTextInterface.onTextSelected(selectedText);
}
});
} else selectedTextInterface.onTextSelected(selectedText);
}
}
});
}
public interface SelectedTextInterface {
void onTextSelected(String selectedText);
}
When you are done with selecting text, just call it with:
webView.getSelectedText(new YourWebView.SelectedTextInterface() {
#Override
public void onTextSelected(String selectedText) {
//Your code here
}
});
I hope this may be useful for some people :-)

Categories

Resources