I started to work with Xamarin Studio a weeks ago, and could not find solution to the next problem:
created an edittext which will contains serial numbers. I'd like ro run a function after the Enter was pressed.
It's working fine, when I press Enter, the function runs without failure, but I can not modify the content of the edittext (I can't type into it).
The code:
EditText edittext_vonalkod = FindViewById<EditText>(Resource.Id.editText_vonalkod);
edittext_vonalkod.KeyPress += (object sender, View.KeyEventArgs e) =>
{
if ((e.Event.Action == KeyEventActions.Down) && (e.KeyCode == Keycode.Enter))
{
//Here is the function
}
};
This is the code of the control:
<EditText
p1:layout_width="wrap_content"
p1:layout_height="wrap_content"
p1:layout_below="#+id/editText_dolgozo_neve"
p1:id="#+id/editText_vonalkod"
p1:layout_alignLeft="#+id/editText_dolgozo_neve"
p1:hint="Vonalkód"
p1:text="1032080293"
p1:layout_toLeftOf="#+id/editText_allapot" />
I tried to use edittext_vonalkod.TextCanged with its arguments, the problem reserved. I can modify the content but can not handle Enter key.
Thanks!
The best approach would be to use the EditorAction event that is designed to be triggered on the Enter key press. It would be a code like this:
edittext_vonalkod.EditorAction += (sender, e) => {
if (e.ActionId == ImeAction.Done)
{
btnLogin.PerformClick();
}
else
{
e.Handled = false;
}
};
And to be able to change the text of the Enter button use imeOptions on your XML:
<EditText
p1:layout_width="wrap_content"
p1:layout_height="wrap_content"
p1:layout_below="#+id/editText_dolgozo_neve"
p1:id="#+id/editText_vonalkod"
p1:layout_alignLeft="#+id/editText_dolgozo_neve"
p1:hint="Vonalkód"
p1:text="1032080293"
p1:layout_toLeftOf="#+id/editText_allapot"
p1:imeOptions="actionSend" />
You need to mark the event as not being handled when the pressed key is ENTER. Place the following code inside your KeyPress handler.
if (e.Event.Action == KeyEventActions.Down && e.KeyCode == Keycode.Enter)
{
// Code executed when the enter key is pressed down
}
else
{
e.Handled = false;
}
try this:
editText = FindViewById(Resource.Id.editText);
editText.KeyPress += (object sender, View.KeyEventArgs e) =>
{
e.Handled = false;
if (e.Event.Action == KeyEventActions.Down && e.KeyCode == Keycode.Enter)
{
//your logic here
e.Handled = true;
}
};
Even better is to create reusable extension to EditText (EditTextExtensions.cs):
public static class EditTextExtensions
{
public static void SetKeyboardDoneActionToButton(this EditText editText, Button button)
{
editText.EditorAction += (sender, e) => {
if (e.ActionId == ImeAction.Done)
{
button.PerformClick();
}
else
{
e.Handled = false;
}
};
}
}
The Android EditText component must be focused. You can force it with:
editText.RequestFocus();
editText.KeyPress += (object sender, View.KeyEventArgs e) =>
{
if ((e.KeyCode == Keycode.Enter))
{
// `enter code here`
}
};
Related
I'm new in android programming but I have a validation function after the user inserts some data like:source point,destination point,...etc
I have 2 spinners :source and destinations ,both include same values..and i want to be able to send a pop up if a user is selecting the same source and destination and the function is this one:
spSursa=is the source spinner
spDestinatie=is the destinations spinner
private boolean validare_Date()
{
if(spSursa.getSelectedItem().toString()!=spDestinatie.getSelectedItem().toString() )
{
if(ratb.isChecked()==false && metrorex.isChecked()==false && both.isChecked()==false)
{
Toast.makeText(getApplicationContext(), R.string.ADAUGA_RUTA_EROARE_TRANSPORT, Toast.LENGTH_SHORT).show();
return false;
}
else
{
return true;
}
}
else {
Toast.makeText(getApplicationContext(), R.string.ADAUGA_RUTA_EROARE_SURSA_DEST, Toast.LENGTH_SHORT).show();
return false;
}
}
Try to change
if(spSursa.getSelectedItem().toString()!=spDestinatie.getSelectedItem().toString() )
To
if(!spSursa.getSelectedItem().toString().equals(spDestinatie.getSelectedItem().toString()))
I have a custom entry field that prevents the soft keyboard from appearing when the entry field get focus. However this prevents the normal focus/unfocus events from occurring. Here is the code for the Android renderer
Control.FocusChange += (sender, eh) =>
{
new Handler().Post(delegate
{
if (eh.HasFocus)
if (Control != null)
{
var imm =
(InputMethodManager)Control.Context.GetSystemService(Android.Content.Context.InputMethodService);
imm.HideSoftInputFromWindow(Control.WindowToken, 0);
}
});
};
Is this a bug in Xamarin or is there a way to have the focus and unfocus events fire.
I had the same problem when trying to hide an already opened soft keyboard when focusing a DatePicker or TimePicker. (In some Android phones the soft keyboard stayed on top of the date/time picker dialogs).
When using Control.FocusChange event handler, the default behaviour of opening the picker dialogs was not being triggered.
Solution:
After hiding the keyboard, call the Focus() method on the element to trigger the normal focus events and default behaviour.
Here is my Android DatePicker renderer code:
protected override void OnElementChanged(ElementChangedEventArgs<DatePicker> e)
{
base.OnElementChanged(e);
if (Control == null)
{
return;
}
Control.ShowSoftInputOnFocus = false;
Control.FocusChange += (sender, args) => HideSoftKeyboard(e.NewElement, args);
}
private void HideSoftKeyboard(DatePicker e, FocusChangeEventArgs args)
{
if (args.HasFocus)
{
Device.BeginInvokeOnMainThread(() =>
{
var inputMethodManager = Context.GetSystemService(Context.InputMethodService) as InputMethodManager;
inputMethodManager?.HideSoftInputFromWindow(Control.WindowToken, HideSoftInputFlags.None);
e?.Focus();
});
}
}
Based on your code, I think you're right to try to dismiss the keyboard in UI thread, I'm not sure that happens with new Handler().Post() here, but you can use BeginInvokeOnMainThread to force the code run on UI thread:
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.FocusChange += (sender, eh) =>
{
if (eh.HasFocus)
{
Device.BeginInvokeOnMainThread(() =>
{
var imm = (InputMethodManager)Control.Context.GetSystemService(Context.InputMethodService);
imm.HideSoftInputFromWindow(Control.WindowToken, HideSoftInputFlags.None);
});
}
};
}
}
This code works by my side and the FocusChange event can be fired normally.
Reference:Change go button to next button in android
I am developing an application with sign up page using Ionic framework.
Is there any option to replace go button with next button? I want to move cursor from one field to another using next button in the keyboard.
you can use following reference to achieve your requirement in ionic.Below code is for cordova
(function($) {
$.fn.enterAsTab = function(options) {
var settings = $.extend({
'allowSubmit': false
}, options);
this.find('input, select, textarea, button').live("keypress", {localSettings: settings}, function(event) {
if (settings.allowSubmit) {
var type = $(this).attr("type");
if (type == "submit") {
return true;
}
}
if (event.keyCode == 13) {
var inputs = $(this).parents("form").eq(0).find(":input:visible:not(disabled):not([readonly])");
var idx = inputs.index(this);
if (idx == inputs.length - 1) {
idx = -1;
} else {
inputs[idx + 1].focus(); // handles submit buttons
}
try {
inputs[idx + 1].select();
}
catch (err) {
// handle objects not offering select
}
return false;
}
});
return this;
};
})(jQuery);
For adding next button , you can refer following link:
How to add Next button in Ionic soft keyboard plugin
THe problem is little difficult to convey, The Actual scenario will be help you guys to understand the real problem.
In the Android Application.
I have a lot of the Jquery Mobile Page append to the android Webview.
When i select one Page (E.g) Profile , the page opens properly and if i press the back button, the application moves to the main page, if i again select profile and press back the application goes to the login page.
if i select some other page and select the profile this is not happening. this issue is not only with the single page. in all the page i have the same issue. Can some one guide me what should i have do?
The Source code of the Key Press event,
enter code here
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && webview.isEnabled()
&& !this.onLogin) {
webview.loadUrl("javascript:handleDeviceBack()");
return true;
} else if (keyCode == KeyEvent.KEYCODE_BACK && this.onLogin) {
moveTaskToBack(true);
}
if (keyCode == KeyEvent.KEYCODE_HOME) {
webview.loadUrl("javascript:handleDeviceHome()");
return true;
}
return false;
}
In my web view,
enter code here
handleDeviceBack = function(status) {
mHealth.util.logMessage('On device Back');
var historyBack = {
"home" : "page",
"loginPage" : "page",
"welcomeMsg" : "page"
};
var moduleIndex = {
"assessNotFound" : "../../home/view/home.html",
"showActivity" : "../../home/view/home.html",
"showMessage" : "../../home/view/home.html",
"show_tracker" : "../../home/view/home.html",
"settingsPage" : "../../home/view/home.html"
};
var graphPages = {
"singlehealthdatapage" : "page",
"multiplehealthdatapage" : "page"
};
var otherShortcuts = {
"show_tracker_view" : "../../trackers/view/showtracker.html",
"detailMessage" : "../../messages/view/showmessage.html",
"alfrescoDIV" : "../../messages/view/showmessage.html"
};
// var exitAppCriteria={ "home" : "page","loginPage" : "page","welcomeMsg" :
// "page"};
if($('.ui-page-active').attr('id')=="condition_index")
{
$.mobile.changePage("../../home/view/history.html");
}
else if (historyBack[$('.ui-page-active').attr('id')]
|| $('body').children().is('#tandcPage')) {
Android.finishActivity();
} else if (moduleIndex[$('.ui-page-active').attr('id')]) {
Android.highlightHome();
$('.ui-alert-wallpaper').detach();
$.mobile.changePage(moduleIndex[$('.ui-page-active').attr('id')]);
} else if (graphPages[$('.ui-page-active').attr('id')]) {
Android.showTab();
Android.pageHistory();
} else if (otherShortcuts[$('.ui-page-active').attr('id')]) {
$.mobile.changePage(otherShortcuts[$('.ui-page-active').attr('id')]);
} else {
$('.dw').detach();
$('.dwo').detach();
$('.dw').detach();
$('.ui-alert-wallpaper').detach();
Android.showTab();
Android.pageHistory();
}
};
I found the problem is with the Android.pageHistory();
enter code here
public void pageHistory() {
this.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
WebContainerActivity.webview.goBack();
}
});
}
Where First time its running properly but if the function called repeatly the web view.go back to the first page.
In your activity override backpressed method like this
#Override
public void onBackPressed() {
webview.loadUrl(sameurl);
}
Hard coded the URL by their ID and solved the issue temporarily.
I am developing an android application in which iIhave 4 edittext and below a button. I want to apply validation on each field so that any field is not left blank. I have tried a lot of samples and applied same logic, but its not working.
I have coded for that. My java class is
http://pastebin.com/ZdeYZPxX
But problem is that when I enter first edittext and then click button, it works. Can anyone help me to come out of this problem?
See I have made this function in class
public boolean checkForEmpty(String fieldString) {
if (fieldString.equalsIgnoreCase("")
|| fieldString.equalsIgnoreCase(null))
return true;
else
return false;
}
Then
username = editUserName.getText().toString().trim();
if (checkForEmpty(username)) {
Showalert("Please enter User ID");
editUserName.requestFocus();
}
After showing a Toast telling the user that one of the EditText is empty you should add a return statement to stop the rest of the code(that starts a new Activity) being run until the user fills all EditTexts:
if (un.equals("") || pw.equals("")) {
if (un.equals("")) {
Toast.makeText(BloodPressureScreen.this, "FirstName is empty", Toast.LENGTH_SHORT).show();
return;
} else {
Toast.makeText(BloodPressureScreen.this, "LastName is empty", Toast.LENGTH_SHORT).show();
return;
}
}
if (cn.equals("") || em.equals("")) {
if (cn.equals("")) {
Toast.makeText(BloodPressureScreen.this, "Contact is empty", Toast.LENGTH_SHORT).show();
return;
} else {
Toast.makeText(BloodPressureScreen.this, "Email is empty", Toast.LENGTH_SHORT).show();
return;
}
}
public boolean checkForEmpty(String fieldStr) {
if (fieldStr.length() == 0 )
return true;
else
return false;
}