Android - Edit Text ... Input from keyboard not accepted - android

In my application, in an activity i have 4 edit Text fields and a button. Only After entering data for all 4 edit text fields, data will be submitted. If one is empty, i am showing an alert dialog stating my custom error message. Now in the activity if i click on edit text and press any key on keyboard, the text is not appened to edit text.
If you have faced a similar issue please do let me know.enter code here
<EditText
android:id="#+id/first_field"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/TextView01"
android:layout_centerHorizontal="true"
android:layout_marginBottom="6dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&apos;."
android:gravity="left|center"
android:hint="First Name"
android:imeOptions="actionNext"
android:inputType="text"
android:textSize="11sp"
android:typeface="sans" >
</EditText>
In .java File
in Oncreate Method
first_field = (EditText)findViewById(R.id.first_field);
InputFilter[] filter = new InputFilter[1];
filter[0] = new InputFilter.LengthFilter(24);
first_field.setFilters(filter);
in Onclick event for the button
NumberKeyListener keyListener1 = new NumberKeyListener() {
public int getInputType() {
return InputType.TYPE_CLASS_TEXT;
}
#Override
protected char[] getAcceptedChars() {
return new char[] { '.','‘' };
}
};
first_field.setKeyListener(keyListener1);

I believe you need to specify android:editable in your xml definition.
According to the setFilters method it "Sets the list of input filters that will be used if the buffer is Editable."

I commented this part of the code in Onclick method and it worked fine.
NumberKeyListener keyListener1 = new NumberKeyListener() {
public int getInputType() {
return InputType.TYPE_CLASS_TEXT;
}
#Override
protected char[] getAcceptedChars() {
return new char[] { '.','‘' };
}
};
first_field.setKeyListener(keyListener1);

editText in change u pot inputtext = true

Related

Programatically created edit text is also getting focus while tapping another edit text in android

I have created multiple edit texts programmatically using existing edit text available in XML file but when the main edit text gets the focus then the edit texts created dynamically also getting focus. My code is as below :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_worker_reg);
existingContact = (EditText)findViewById(R.id.workerPhone);
drawable = existingContact.getBackground();
}
public void addAnotherContactNumber(View view) {
final CharSequence[] options = { "Work", "Home","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(WorkerRegActivity.this);
builder.setTitle("Add Contact Number!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Work"))
{
linearLayout = (LinearLayout)findViewById(R.id.containerLayout);
EditText newContact = new EditText(WorkerRegActivity.this);
newContact.setHint("Phone NO." + (newContactIndex - 1));
newContact.setHintTextColor(existingContact.getHintTextColors());
newContact.setInputType(existingContact.getInputType());
newContact.setLayoutParams(existingContact.getLayoutParams());
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
newContact.setBackgroundDrawable(drawable);
} else {
newContact.setBackground(drawable);
}
linearLayout.addView(newContact, newContactIndex);
newContactIndex += 1;
contactList.add(newContact);
}
else if (options[item].equals("Home"))
{
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
Actually I want to create multiple edit texts using an existing edit text as defined in XML file with same background but when one edit text gains focus another one also gains the focus automatically. Please help.....
When you add new editTexts, just add a property line switching off the focus :
edittext.clearFocus();
where edittext is the id of your edittext.
If this doesn'twork, you can use this :
<!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
android:focusable="true" android:focusableInTouchMode="true"
android:layout_width="0px" android:layout_height="0px"/>
<!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component
to prevent the dummy from receiving focus again -->
<AutoCompleteTextView android:id="#+id/autotext"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:nextFocusUp="#id/autotext" android:nextFocusLeft="#id/autotext"/>
This is just aworkaround to trick android to give focus to something else than the edit text. Remember, however, that you have to put the dummy element just before the editText you wish to revoke focus from.
While doing such thing we should use different object of drawable rather than same instance.
Drawable clone = drawable.getConstantState().newDrawable();

Android EditText .setText("") not working

I am trying to clear the text in my edit text field but for some reason it is not working.
I have declared an edit text field in the xml of my view:
<EditText
android:id="#+id/enterGlucoseLevel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mySimpleXYPlot"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="numberDecimal" />
I have used the attribute onClick to link my button to the enterGlucoseAction() method in my MainActivity class:
<Button
android:id="#+id/enterGlucoseButton"
android:clickable="true"
android:onClick= "enterGlucoseAction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/enterGlucoseLevel"
android:layout_centerHorizontal="true"
android:text="#string/enterGlucoseLvlButton" />
Here is that method:
public void enterGlucoseAction(View v) {
glucoseField.setText("");
Toast.makeText(v.getContext(), "You clicked the button", Toast.LENGTH_SHORT).show();
}
I get the toast pop up but my edit text field is not being cleared.
Here is my on create and instance variables in case the problem lies there.
private XYPlot plot;
private Button addGlucoseLevel;
private EditText glucoseField;
private XYSeries currentSeries;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addGlucoseLevel = (Button) findViewById(R.id.enterGlucoseButton);
glucoseField = (EditText) findViewById(R.id.enterGlucoseLevel);
currentSeries = new SimpleXYSeries(Arrays.asList(new Number[] { 7200, 8, 54000, 2, 64800, 4 }),
SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED,
"Glucose Level");
//Create an series of numbers to plot.
createGraph(currentSeries);
}
Thanks in advance.
And sorry, I know this has been asked before but I can't find a solution to my problem specifically.
To clear your EditText which accepts numbers use clear() method:
glucoseField.getText().clear();
You can try setting it this way:
((EditText)findViewById(R.id.enterGlucoseLevel)).getText().clear();
Alternatively you can use getText().clear(); just replace glucoseField.setText(""); with glucoseField.getText().clear();
You should use
setText("\b");
As we can use escape sequence
((EditText)findViewById(R.id.yourEditTextId)).getText().clear();
anything else crashed.

How to display cursor at the end of text in TextView?

I wanted to display blinking cursor at the end of the text in TextView .
I tried by android:cursorVisible="true" in TextView But no go .
Even i tried text.setCursorVisible(true); Doesn't work .
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:cursorVisible="true"
android:textCursorDrawable="#null" />
Does any one know any solution for it ?
First of all you should use EditText in place of TextView for taking input. If still the cursor doesn't blink, set the android:cursorVisible="true"attribute in xml file, it should make the cursor blink. If your cursor is not visible in edit text, that's also a reason one can't see the cursor blinking. Set android:textCursorDrawable="#null". This should solve your problem
<EditText
android:id="#+id/editext1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textCursorDrawable="#null"
android:cursorVisible="true">
</EditText>
In your activity class, add this code as well.
EditText input = (EditText)findViewById(R.id.edittext1);
input.setSelection(input.getText().length());
There is a solution for this.
I had to do this when I was making a terminal app and I used a simple runnable put a cursor at the end and make it blink.
I made 3 class variables:
private boolean displayCursor;
private boolean cursorOn;
private String terminalText;
private TextView terminal; // The TextView Object
terminalText keeps track of the text to be displayed.
Created a class method that runs the runnable the first time
private void runCursorThread() {
Runnable runnable = new Runnable() {
public void run() {
if (displayCursor) {
if (cursorOn) {
terminal.setText(terminalText);
} else {
terminal.setText(terminalText + '_');
}
cursorOn = !cursorOn;
}
terminal.postDelayed(this, 400);
}
};
runnable.run();
}
And initiated the variables and called runCursorThread() in onCreate()
cursorOn = false;
displayCursor = true;
runCursorThread();
I think you should go for EditText. You can set its background and make it appears like TextView with below code.
Step 1
<EditText
android:id="#+id/edtText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent" >
</EditText>
Step 2
EditText edt = (EditText) findViewById(R.id.edtText);
edt.setSelection(edt.getText().length());
Output
Finally Fixed this Using the EditText as per #Chintan Rathod advice.
<EditText
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"/> //reference to #Chintan Rathod.
Code
EditText text=(EditText) findViewById(R.id.text);
text.setText("hello");
text.setSelection(text.getText().length()); // reference to #Umer Farooq code.

FormEditText not clearing after correct input

I use the FormEditText widget for a form (obviously). Thing is: After being tested not valid once, the warning red exclamation mark won't disappear even after entering a correct input and the field.testValidity() returning true. I also haven't found a method of FormEditText to manually clear it.
Anyone else experienced this?
This is the method I use when the send button is tapped from the action bar:
public boolean checkFields() {
FormEditText[] allFields = { firstname, lastname, street, zip, city,
email, phone };
boolean allValid = true;
FormEditText firstFailedField = null;
for (FormEditText field : allFields) {
if (!field.testValidity()) {
Log.d("FOR", "failed field: " + field.getHint());
allValid = false;
if (firstFailedField == null) {
firstFailedField = field;
}
}
}
if (allValid) {
} else {
firstFailedField.requestFocus();
}
return allValid;
}
And this is part of my layout:
<com.andreabaccega.widget.FormEditText
android:id="#+id/firstname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ems="10"
android:hint="Vorname"
android:inputType="textPersonName"
android:singleLine="true"
whatever:customRegexp="[a-zA-Z]{2,}"
whatever:emptyErrorString="Bitte Vornamen angeben"
whatever:testErrorString="Bitte Vornamen angeben"
whatever:testType="regexp" >
</com.andreabaccega.widget.FormEditText>
<com.andreabaccega.widget.FormEditText
android:id="#+id/lastname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ems="10"
android:hint="Nachname"
android:inputType="textPersonName"
android:singleLine="true"
whatever:customRegexp="[a-zA-Z]{2,}"
whatever:emptyErrorString="Bitte Nachnamen angeben"
whatever:testErrorString="Bitte Nachnamen angeben"
whatever:testType="regexp" >
</com.andreabaccega.widget.FormEditText>
I entered Kim in the firstname field, pressed send. Theres a warning on the lastname field. Enter Jong in the lastname field, but the exclamation mark won't hide. And the field does test valid!
As suggested I'll post my comment as an answer:
You can try field.setError(null): in this way you can hide the error from an EditText. It should work for FormEditText since FormEditText extends EditText.

Make EditText ReadOnly

I want to make a read-only EditText view. The XML to do this code seems to be android:editable="false", but I want to do this in code.
How can I do this?
Please use this code..
Edittext.setEnabled(false);
If you setEnabled(false) then your editText would look disabled (gray, etc). You may not want to change the visual aspect of your editor.
A less intrusive way would be to use setFocusable(false).
I believe that this answers your question closer to your initial intent.
In XML use:
android:editable="false"
As an example:
<EditText
android:id="#+id/EditText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:editable="false" />
This works for me:
EditText.setKeyListener(null);
editText.setInputType(InputType.TYPE_NULL);
As per the docs this prevents the soft keyboard from being displayed. It also prevents pasting, allows scrolling and doesn't alter the visual aspect of the view. However, this also prevents selecting and copying of the text within the view.
From my tests setting setInputType to TYPE_NULL seems to be functionally equivalent to the depreciated android:editable="false". Additionally, android:inputType="none" seems to have no noticeable effect.
android:editable="false" has been deprecated. Therefore you cant use it to make the edit text readonly.
I have done this using the bellow solution. Here I have used
android:inputType="none"
android:textIsSelectable="true"
android:focusable="false"
Give it try :)
<EditText
android:id="#+id/et_newsgpa_university"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="#string/hint_educational_institute"
android:textSize="#dimen/regular_text"
android:inputType="none"
android:textIsSelectable="true"
android:focusable="false"
android:maxLines="1"
android:imeOptions="actionNext"/>
The best is by using TextView instead.
editText.setEnabled(false);
editText.setFilters(new InputFilter[] { new InputFilter() {
public CharSequence filter(CharSequence src, int start, int end,
Spanned dst, int dstart, int dend) {
return src.length() < 1 ? dst.subSequence(dstart, dend) : "";
}
} });
This will give you uneditable EditText filter. you first need to put the text you want on the editText field and then apply this filter.
writing this two line is more than enough for your work.
yourEditText.setKeyListener(null);
yourEditText.setEnabled(false);
set in XML
android:inputType="none"
Try using
editText.setEnabled(false);
editText.setClickable(false);
Try overriding the onLongClick listener of the edit text to remove context menu:
EditText myTextField = (EditText)findViewById(R.id.my_edit_text_id);
myTextField.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return true;
}
});
android:editable
If set, specifies that this TextView has an input method. It will be a textual one unless it has otherwise been specified. For TextView, this is false by default. For EditText, it is true by default.
Must be a boolean value, either true or false.
This may also be a reference to a resource (in the form #[package:]type:name) or theme attribute (in the form ?[package:][type:]name) containing a value of this type.
This corresponds to the global attribute resource symbol editable.
Related Methods
If you just want to be able to copy text from the control but not be able to edit it you might want to use a TextView instead and set text is selectable.
code:
myTextView.setTextIsSelectable(true);
myTextView.setFocusable(true);
myTextView.setFocusableInTouchMode(true);
// myTextView.setSelectAllOnFocus(true);
xml:
<TextView
android:textIsSelectable="true"
android:focusable="true"
android:focusableInTouchMode="true"
...
/>
<!--android:selectAllOnFocus="true"-->
The documentation of setTextIsSelectable says:
When you call this method to set the value of textIsSelectable, it sets the flags focusable, focusableInTouchMode, clickable, and longClickable to the same value...
However I had to explicitly set focusable and focusableInTouchMode to true to make it work with touch input.
Use this code:
editText.setEnabled(false);
editText.setTextColor(ContextCompat.getColor(context, R.color.black);
Disabling editText gives a read-only look and behavior but also changes the text-color to gray so setting its text color is needed.
this is my implementation (a little long, but useful to me!):
With this code you can make EditView Read-only or Normal. even in read-only state, the text can be copied by user. you can change the backgroud to make it look different from a normal EditText.
public static TextWatcher setReadOnly(final EditText edt, final boolean readOnlyState, TextWatcher remove) {
edt.setCursorVisible(!readOnlyState);
TextWatcher tw = null;
final String text = edt.getText().toString();
if (readOnlyState) {
tw = new TextWatcher();
#Override
public void afterTextChanged(Editable s) {
}
#Override
//saving the text before change
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
// and replace it with content if it is about to change
public void onTextChanged(CharSequence s, int start,int before, int count) {
edt.removeTextChangedListener(this);
edt.setText(text);
edt.addTextChangedListener(this);
}
};
edt.addTextChangedListener(tw);
return tw;
} else {
edt.removeTextChangedListener(remove);
return remove;
}
}
the benefit of this code is that, the EditText is displayed as normal EditText but the content is not changeable. The return value should be kept as a variable to one be able revert back from read-only state to normal.
to make an EditText read-only, just put it as:
TextWatcher tw = setReadOnly(editText, true, null);
and to make it normal use tw from previous statement:
setReadOnly(editText, false, tw);
This worked for me, taking several of the suggestions above into account. Makes the TextEdit focusable, but if user clicks or focuses, we show a list of selections in a PopupWindow. (We are replacing the wacky Spinner widget). TextEdit xml is very generic...
public void onCreate(Bundle savedInstanceState) {
....
fEditState = (EditText) findViewById(R.id.state_edit);
fEditState.setLongClickable(false);
fEditState.setKeyListener(null);
fEditState.setFocusable(true);
fEditState.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus)
{
showStatesPopup();
}
}
});
fEditState.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0)
{
showStatesPopup();
}
});
....
}
private void showStatesPopup()
{
// fPopupWindowStates instantiated in OnCreate()
if (!fPopupWindowStates.isShowing()) {
// show the list view as dropdown
fPopupWindowStates.showAsDropDown(fEditState, -5, 0);
}
}
This was the only full simple solution for me.
editText.setEnabled(false); // Prevents data entry
editText.setFocusable(false); // Prevents being able to tab to it from keyboard
As android:editable="" is deprecated,
Setting
android:clickable="false"
android:focusable="false"
android:inputType="none"
android:cursorVisible="false"
will make it "read-only". However, users will still be able to paste into the field or perform any other long click actions. To disable this, simply override onLongClickListener().
In Kotlin:
myEditText.setOnLongClickListener { true }
suffices.
My approach to this has been creating a custom TextWatcher class as follows:
class ReadOnlyTextWatcher implements TextWatcher {
private final EditText textEdit;
private String originalText;
private boolean mustUndo = true;
public ReadOnlyTextWatcher(EditText textEdit) {
this.textEdit = textEdit;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (mustUndo) {
originalText = charSequence.toString();
}
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if (mustUndo) {
mustUndo = false;
textEdit.setText(originalText);
} else {
mustUndo = true;
}
}
}
Then you just add that watcher to any field you want to be read only despite being enabled:
editText.addTextChangedListener(new ReadOnlyTextWatcher(editText));
I had no problem making EditTextPreference read-only, by using:
editTextPref.setSelectable(false);
This works well when coupled with using the 'summary' field to display read-only fields (useful for displaying account info, for example). Updating the summary fields dynamically snatched from http://gmariotti.blogspot.com/2013/01/preferenceactivity-preferencefragment.html
private static final List<String> keyList;
static {
keyList = new ArrayList<String>();
keyList.add("field1");
keyList.add("field2");
keyList.add("field3");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
for(int i=0;i<getPreferenceScreen().getPreferenceCount();i++){
initSummary(getPreferenceScreen().getPreference(i));
}
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
//editTextPref.setEnabled(false); // this can be used to 'gray out' as well
editTextPref.setSelectable(false);
if (keyList.contains(p.getKey())) {
p.setSummary(editTextPref.getText());
}
}
}
Set this in EdiTextView xml file
android:focusable="false"
in java file:
Edittext.setEnabled(false);
in xml file:
android:editable="false"
These 2 lines makes ur edittext selectable and at the same time not editable (it doesn't even show the soft keyboard):
editText.setInputType(InputType.TYPE_NULL);
editText.setTextIsSelectable(true);

Categories

Resources