I am making an application and I have added an EditText in my layout.
What I'm trying to achieve is that when EditText is selected should open a dialog box, with some general text and an OK button. Which method can I use to accomplish this?
You must try some thing like this
searchtext.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
showDialog();
}
}
};
and here goes showDialog() code
private void showDialog()
{
final AlertDialog.Builder Main_Dialog = new AlertDialog.Builder(this);
final EditText input = new EditText(this);
input.setPadding(10, 10, 10, 10);
input.setText(ipAddress);
Main_Dialog.setView(input);
Main_Dialog.setTitle("Enter IP Address:");
Main_Dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
//Do whatever
}
});
Main_Dialog.show();
}
If I'm reading your dilemma correctly, you'd set an OnFocusChangeListener for the EditText. Something like the following snip.
EditText e = new EditText(this);
e.setOnFocusChangeListener
(
new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (v.hasFocus()) {
showDialog(COOL_DIALOG);
}
}
}
);
Note, this seems like a somewhat odd user interaction. Why not just have them use the EditText for what it was made for? If you really want to do this, I'd suggest using a regular TextView or Button and use a click handler to pop the dialog. This would create a more "expected" interaction for the user.
You mean you want to display the dialog when your EditView gets focus? I think overriding View.onFocusChanged() would be the way to go. If you want to track the detailed input into EditText, implement TextWatcher and use TextView.addTextChangedListener() to add it to the EditText instance.
Related
With a Button it is simple,
<Button
android:blablabla="blabla"
...
android:onClick="doSomething" />
this will preform the doSomething(View) function.
How can we mimic this with an EditText ?
I have read about this and i read that most people use an imeOptions (which still seems necessary) and then implement a actionListener on that EditText object.
This is were i'm lost.
Is there a way to implement the "Done"-action (or send or...) from our keyboard to a onClick function like we do with a Button, or do we need to explicitly implement the listener ?
Regards !
The below code will perform some action when you press the Done key in the softkeyboard.
editText.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId==EditorInfo.IME_ACTION_DONE){
//do your actions here that you like to perform when done is pressed
//Its advised to check for empty edit text and other related
//conditions before preforming required actions
}
return false;
}
});
Hope it helps !!
I am assuming what you are wanting to do is run some code when the EditText is clicked?
If so, I have found a solution from another thread on the site:
EditText myEditText = (EditText) findViewById(R.id.myEditText);
myEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
then do this code here
}
}
});
via: A better way to OnClick for EditText fields?
I'm trying to override the soft input keyboard for a singular EditText field. I've mostly been following this excellent example -- setting the XML to inputType="text", and then, within the onCreate:
EditText amount = (EditText) findViewById(R.id.amount_edit_text);
final EditText amt = amount;
amount.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showCustomKeyboard(v);
} else {
hideCustomKeyboard();
}
}
});
amount.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCustomKeyboard(v);
}
});
amount.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
EditText edittext = (EditText) v;
int inType = edittext.getInputType();
edittext.setInputType(InputType.TYPE_NULL);
edittext.onTouchEvent(event);
edittext.setInputType(inType);
return true;
}
});
This works for the most part -- clicking on the EditText brings up my custom keyboard, but there's always a jump. It's very quick, but it'll show my keyboard stacking on top of the standard keyboard, and then the standard keyboard will collapse and my keyboard will be left. And at times, it will arbitrarily not collapse and simply just stack...
Is there any way to override the standard keyboard with my own without this jump?
I ended up using a Runnable to close the standard keyboard before showing my custom keyboard. It's not quite perfect, but it doesn't stack the two keyboards like it used to. I'll keep looking for a better solution though.
within the else statement of my OnFocusChangeListener:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
showCustomKeyboard(v);
}
}, 250);
((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(v.getWindowToken(), 0);
Try to hide the softKeyboard when you are showing yours, using the following code:
InputMethodManager mgr = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(amount.getWindowToken(), 0);
Found two solutions - please see selected answer
When the user clicks in a certain region of an EditText, I want to popup a dialog. I used onClick to capture the click. This partially works: the first time the user taps the EditText, the soft keyboard pops up and the dialog doesn't. Subsequent taps bring up the keyboard and then the dialog (and the keyboard disappears).
I suspect this has something to do with the EditText gaining focus.
Here's a code snip:
public class PrefixEditText extends EditText implements TextWatcher, OnClickListener
{
public PrefixEditText (Context context)
{
super (context);
setOnClickListener (this);
}
#Override
public void onClick(View v)
{
int selStart = getSelectionStart();
if (selStart < some_particular_pos)
bring_up_dialog();
}
}
IMPORTANT: I don't want to completely disable the normal EditText behavior. I want the user to be able to make region selections (for copy & paste). I probably still want it to gain focus (so I don't break the model when people with physical keyboards use the app). And it's ok for the click to set the cursor position. Thus, solutions that override onTouch and block all onTouch actions from the EditText will not work for me.
UPDATE I've discovered a bit more. If the EditText is gaining focus, onFocusChange gets called and onClick does not. If it already has focus, onClick gets called and onFocusChange does not.
Secondly, it's possible to hide the keyboard by calling
setInputType (InputType.TYPE_NULL);
Doing so in onFocusChange works - the keyboard never shows up. Doing so in onClick (assuming the keyboard was hidden before the click) apparently is too late - the keyboard shows up and then disappears.
The next idea to try would be to hide the keyboard during onTouch. However, I'm afraid to mess with that code - seems that whatever I figure out would be very fragile with respect to future versions of EditText.
Any thoughs on this?
May be this can work
EditText e = new EditText(context);
e.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(hasFocus)
{
//dialogue popup
}
}
});
or u can use e.hasFocus(); and then use e.setFocusable(false); to make it unfocus
/////////////// my code
e.setInputType(InputType.TYPE_NULL);
e.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder sa = new Builder(ctx);
sa.create().setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
e.setInputType(InputType.TYPE_CLASS_TEXT);
}
});
sa.show();
}
});
try change capture click by onClick to onTouch
this.editText.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//dialogue popup
}
return false;
}
});
try this if it can help u.first time the edittext will behave as a normal editttext and on condition u can show the dialog as needed
EditText editText;
mTim_edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
//statement
if(condition){
AlertDialog diaBox = Utils.showErrorDialogBox( "Term in Months Cannot be 0", context);
diaBox.show();
}
}
}
});
After lots of experiments, here are two working solutions! I tested them on my two devices - Nexus 7 running 4.2.1, Kyocera C5170 runing 4.0.4. My preference is Solution 2.
SOLUTION 1
For the first, the trick was to determine the cursor position in onTouch instead of onClick, before EditText has a chance to do it's work - particularly before it pops up the keyboard.
One additional comment: be sure to set android:windowSoftInputMode="stateHidden" in your manifest for the popup, or you'll get the keyboard along with the popup.
Here's the whole code:
public class ClickText extends EditText implements OnTouchListener
{
public ClickText (Context context, AttributeSet attrs)
{
super (context, attrs);
setOnTouchListener (this);
}
#Override
public boolean onTouch (View v, MotionEvent event)
{
if (event.getActionMasked() == MotionEvent.ACTION_DOWN)
{
int line = getLayout().getLineForVertical ((int)event.getY());
int onTouchCursorPos = getLayout().getOffsetForHorizontal (line, event.getX());
if (onTouchCursorPos < 10) // or whatever condition
showPopup (this); // or whatever you want to do
}
return false;
}
private void showPopup (final EditText text)
{
Intent intent = new Intent (getContext(), Popup.class);
((Activity)getContext()).startActivity (intent);
}
}
SOLUTION 2
This one is actually simpler and, I think, is better - fewer side effects.
Here, the trick is to let EditText do all its click processing and then override it asynchronously. The gist is: wait for the touch to "let go" - MotionEvent.ACTION_UP - and then instead of doing your action right then, post a Runnable to the event queue and do your action there.
The whole code:
public class ClickText extends EditText implements OnTouchListener
{
public ClickText (Context context, AttributeSet attrs)
{
super (context, attrs);
setOnTouchListener (this);
}
#Override
public boolean onTouch (View v, MotionEvent event)
{
switch (event.getActionMasked())
{
case MotionEvent.ACTION_UP:
{
post (new Runnable ()
{
// Do this asynch so that EditText can finish setting the selectino.
#Override
public void run()
{
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
// If selStart is different than selEnd, user has highlighed an area of
// text; I chose to ignore the click when this happens.
if (selStart == selEnd)
if (selStart >= 0 && selStart < 10) // or whatever range you want
showPopup (this);
}
});
break;
}
}
return false;
}
private void showPopup (final EditText text)
{
Intent intent = new Intent (getContext(), Popup.class);
((Activity)getContext()).startActivity (intent);
}
}
use this below code snippet
this.editText.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//dialogue popup
}
return false;
}
});
I would like an AlertDialog with an EditText field in it to accept input. This in itself is pretty straight-forward. However there are a few "obvious" features that I would like as fallout from this request. I'll take them one-by-one. I am looking for anyone that has a simpler solution to these things. I am guessing the solution is, "Write your own custom dialog you lazy bum."
AlertDialog with an EditText
final EditText input = new EditText(context);
final AlertDialog dlg = new AlertDialog.Builder(this).
setTitle("Title").
setView(input).
setCancelable(false).
setPositiveButton(android.R.string.ok, new OnClickListener()
{
#Override
public void onClick(final DialogInterface dialog, final int which)
{
/* Handle ok clicked */
dialog.dismiss();
}
}).
setNegativeButton(android.R.string.cancel, new OnClickListener()
{
#Override
public void onClick(final DialogInterface dialog, final int which)
{
/* Handle cancel clicked */
dialog.dismiss();
}
}).create();
dlg.show();
Yay, works great. It'd sure be nice if that input field got focused right away (and show the keyboard), right?
AlertDialog with focused EditText
The following code would be after create() and before dlg.show()
/** This requires API Level 8 or greater. */
dlg.setOnShowListener(new OnShowListener()
{
#Override
public void onShow(final DialogInterface dialog)
{
input.requestFocus();
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(input, 0);
}
});
Nice job... I guess. Now that I have this focused input it'd be nice if it respected the inputs IME option...
AlertDialog with focused EditText with a custom IME Option
input.setImeOptions(EditorInfo.IME_ACTION_DONE);
input.setOnEditorActionListener(new OnEditorActionListener()
{
#Override
public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event)
{
/** Same code here that goes in the dialog.setPositiveButton OnClickListener */
dlg.dismiss();
return true;
}
});
Now that's really not a great solution (repeated code) but it works...
Do people have a better way of solving this problem, or is it really that rare to ask a user for a small piece of information in a dialog, or am I just a winer and should go write my own dialog?
As per comments on the OP:
You do not have to have such repeated code in the OnEditorActionListener. Instead of repeating the code, you can tell the OS to click the "Ok" button when it is activated.
Something like this:
public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event) {
dlg.getButton(DialogInterface.BUTTON_POSITIVE).performClick(); // Click OK button
return true;
}
Overall I would say you are taking the right approach (documentation about collecting information through dialogs). As I mentioned in a comment, the OS uses an AlertDialog w/ EditText for adding dictionary words (to the user dictionary), so this is an expected functionality in the OS.
You can always switch to an Activity with Theme.Dialog theme or a DialogFragment which gives you a lot more freedom in tuning your widgets. AlertDialogs are probably better for displaying information. Hope this helps.
In my application when I click an EditText, I have to perform some logic. I have the code. But it is not going into the click method.
My code:
EditText des=(EditText)findViewById(R.id.desinc);
des.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
java.lang.System.out.println("Inside click");
EditText income=(EditText)findViewById(R.id.editText1);
// TODO Auto-generated method stub
String inc=income.getText().toString();
int indexOFdec = inc.indexOf(".");
java.lang.System.out.println("index="+indexOFdec);
if(indexOFdec==0)
{
java.lang.System.out.println("inside index");
income.setText(inc+".00");
}
}
});
What am I doing wrong? Help me.
Try overriding onTouch by setting up an onTouchListener in the same way as an onClickListener. Use this code as a reference.
EditText dateEdit = (EditText) findViewById(R.id.date);
date.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
//anything you want to do if user touches/ taps on the edittext box
}
return false;
}
});
UPDATE(why this behavior):
The first click event focuses the control, while the second click event actually fires the OnClickListener. If you disable touch-mode focus with the android:focusableInTouchMode View attribute, the OnClickListener should fire as expected.
You can also try this: set android:focusableInTouchMode="false" for your EditText box in the xml. See if it works with the existing code.
You should use OnFocusChangeListener()
Try clicking EditText twice because at first instance EditText gets focus and after that EditText's click event executes. So, if you want your code to execute on first click write your code for focus change of EditText using OnFocusChangeListener().