So I've got what seems to be a common problem, which is that the EditText in my dialog box doesn't show up when it gets focus. I've seen several workarounds, such as in this thread, this one and this one (and many more), but I have never seen a satisfactory explanation for why this is happening in the first place.
I would much prefer to have android use its own default behavior for EditTexts than to build my own, but it seems like everyone (in those threads) has accepted that the default behavior for EditTexts in Dialogs is to just give a cursor and no keyboard. Why would that be?
For the record, none of these workarounds seem to be working for me - the closest I've been able to come is forcing a keyboard to appear underneath the dialog box (using InputMethodManager.toggleSoftKeyboard(*)). My particular configuration is API15, the EditText shows up in a footer on a ListView within an AlertDialog. The EditText android:focusable="true" is set, and onFocusChangeListener is receiving focus events.
Edit:
As requested, here is the specific code snippet that I'm working with. I won't bother with the whole layout, but in this specific application, the EditText appears in response to pressing a button on the dialog (similar to an action view). It is contained in a RelativeLayout which by default has visibility "gone":
<RelativeLayout
android:id="#+id/relLay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:visibility="gone"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp">
<ImageButton
android:id="#+id/cancelBut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#color/transparent"
android:src="#drawable/cancelButton"
android:layout_margin="5dp"/>
<ImageButton
android:id="#+id/okBut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/cancelBut"
android:background="#color/transparent"
android:src="#drawable/okButton"
android:layout_margin="5dp" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:focusable="true"
android:layout_toLeftOf="#id/okBut"/>
</RelativeLayout>
The code which builds this sets the visibility of the relativeLayout to "Visible" (and hides the other UI elements). This should be enough to pull up the keyboard when the EditText gets focused, based on my experience with EditText. However, for some reason this is not the case. I can set the following onFocusChangeListener:
edit_text.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// For whatever reason we need to request a soft keyboard.
InputMethodManager imm = (InputMethodManager)dlg.getWindow().getContext().getSystemService(_Context.INPUT_METHOD_SERVICE);
if(hasFocus)
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
Log.v("DialogProblem", "Focus requested, " + (hasFocus?"has focus.":"doesn't have focus."));
}
}
});
Using this configuration, when I first enter the EditText, the onFocusChangedListener triggers, and generates a log that invariably looks like this:
Focus requested, has focus.
Focus requested, doesn't have focus.
Focus requested, has focus.
The keyboard shows up and then disappears, probably because I toggle it twice, but even when I make sure it stays up, it's behind the dialog window (in a greyed out area), and there's no way to get to it without closing the dialog.
That said, I'd like to emphasize that even though I may be able to get this work-around to work, I'm primarily interested in finding a simple reason why the EditText isn't triggering in the first place, and why this seems to be so commonplace!
OK, so after reading a lot, I have figured out why this is a problem, and I do not need to use any workarounds.
The problem seems to be (at least in my case), that since the place where you enter text is hidden initially (or nested or something), AlertDialog is automatically setting the flag WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM (or some combination of that and WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) so that things don't trigger a soft input to show up.
The way that I've found to fix this is to add the following line after the dialog has been created:
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
Once this is done, the EditText acts like a normal EditText, no kludges or workarounds necessary.
I have the same problem in my own app. If you are developing for API level >= 8 you can use this snippet:
dialog.setOnShowListener(new OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(textEdit, InputMethodManager.SHOW_IMPLICIT);
}
});
I haven't found a solution for lower API levels...
BTW: This snippet doesn't always work on emulator. I don't know why.
If you read the AlertDialog documentation you'll find there:
The AlertDialog class takes care of automatically setting *WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM* for you based on whether any views in the dialog return true from View.onCheckIsTextEditor(). Generally you want this set for a Dialog without text editors, so that it will be placed on top of the current input method UI. You can modify this behavior by forcing the flag to your desired mode after calling onCreate.
I had the problem you've mentioned with EditText in ListView inside a Dialog. I fixed it by overwriting the custom view class (in my case ListView) with my own FocusableListView, with just one method overwritten:
public class FocusableListView extends ListView {
public FocusableListView(Context context) {
super(context);
}
public FocusableListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FocusableListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public boolean onCheckIsTextEditor() {
// this is where the magic happens
return true;
}
}
Then I'm using it in the layout file as:
<?xml version="1.0" encoding="UTF-8"?>
<com.myexample.wiget.FocusableListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:descendantFocusability="beforeDescendants"
android:layout_height="wrap_content" />
You can overwrite the RelativeLayout in your case the same way and it should work.
This is what worked for me. Create the AlertDialog.Builder, set title, positiveButton, negativeButton. After do this:
AlertDialog dialog = builder.create();
dialog.getWindow().clearFlags( WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
editText.requestFocus();
You don't need to use builder.show();.
The code above is very helpfull. But you must call the "show" method after the "create" method (I don't know why, but only this works in my dialog with EditText in ListView).
In method onCreateDialog:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case YOUR_DIALOG_ID: {
//...
AlertDialog a = new AlertDialog.Builder(this)./*
... set the properties here
*/
.create();
a.show(); //!!! this is very important to call the "show" method
a.getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
return a;
}
//...
}
return null;
}
Thank you! I have an embedded TextEdit in the last row of ListView embedded in the alert dialog fragment. I used your solution of clearing the flags as a post runnable and now it works perfectly.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("My Title");
m_adapter = new MyAdapter(getContext());
builder.setAdapter(m_adapter, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
final AlertDialog dialog = builder.create();
final ListView listView = dialog.getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
listView.post(new Runnable() {
#Override
public void run() {
dialog.getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
}
});
return dialog;
}
Here's one way to do it:
final Window dialogWindow = dialog.getWindow();
dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
I would like to add on to Paul's answer and Alexander's comment.
I myself have a dialog that's created in the onCreateDialog() method, which (seems to) require returning dialog.show();, wherefore you can not add the layoutparams to the dialog where the dialog is created. To work around this, just keep your onCreateDialog() method the same, and add an onResume() method as follows:
#Override
public void onResume() {
super.onResume();
Dialog dialog = getDialog();
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
This should do the trick, it works for me, thankfully. Have been on this case for quite some while.
full code for showing the keyboard in dialog:
public void onFocusChange(View v, boolean hasFocus) {
Log.v("onFocusChange", hasFocus + " " + showkeyboard);
if (hasFocus) {
if (showkeyboard++ == 0) {
alertDialog.getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
alertDialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
} else {
showkeyboard = 1;
}
}
}
This worked for me ----
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
//dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
//dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
InputMethodManager mgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(v, InputMethodManager.SHOW_FORCED);
editText.setFocusable(true);
}
});
just add below codeLine:
// to show keyboard automatically while editText is in dialog
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Related
I have a customized dialog which i have created using DialogFragment. it uses a view which got one button and an edittext.
in my edittext, i have implemented a textwatcher where if there are values in the edittext, the button becomes visible else it remains invisible.
public class ShowDialog extends DialogFragment {
private Button btnShowBalance;
private EditText balanceInquiryPinInput;
public ShowDialog(){
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView = inflater.inflate(R.layout.fragment_balance_inquiry,null);
btnShowBalance= (Button) myView.findViewById(R.id.btnShowBalance);
balanceInquiryPinInput = (EditText) myView.findViewById(R.id.et_balance_inquiry_pin);
balanceInquiryPinInput.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) {
if(s.length() > 0){
btnShowBalance.setVisibility(View.VISIBLE);
}else{
btnShowBalance.setVisibility(View.INVISIBLE);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
btnShowBalance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showBalance(balanceInquiryPinInput,nameview,ShowDialog.this);
}
});
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(myView);
// Create the AlertDialog object and return it
return builder.create();
}
}
Problem
When i change my screen orientation to (let say) landscape, if i had typed anything to my edittext before changing my orientation, whatever i had typed is still visible in landscape, my button is visible But it becomes unclickable. i cannot click it. i have to remove the dialog by pressing somewhere outside the dialog window or back button and create it again.
How can i make my button remain clickable even when one change the screen orientation?
Note: it is clickable before changing orientation.
EDIT
My dialog is activated by a button which is in a fragment and not activity.
this question is not a duplicate of This one because the latter is an implentation on an activity and it's implementation is unreliable to my view and it's state in question(button)
EDIT xml for my custom dialog layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#044848"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal"
android:background="#drawable/check_balance"
>
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/et_balance_inquiry_pin"
android:layout_marginTop="5dp"
android:gravity="center"
android:background="#drawable/enter_pin_textview"
android:inputType="numberPassword"/>
<Button
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="OK"
android:id="#+id/btnShowBalance"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
android:textColor="#android:color/white"
android:textSize="20sp"
android:background="#drawable/show_balance_ok_button"
android:visibility="invisible" />
</LinearLayout>
The problem of the button being disabled may be due to the dialog no longer being functional due to the calling view being destroyed in the orientation change. So it may still be visible, but is really an artifact of the previous view before it was destroyed.
You need to use methods that saves the state of your dialog fragment instance when it is created. for example you can call
setRetainInstanceState(true);
in your onCreateDialog method to retain the state of your DialogFragment instance when screen orientation changes.
You may need to overide onDestroyView() to prevent dialog from been destroyed when screen orientation changes. like this
#Override
public void onDestroyView() {
if (getDialog() != null && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
Information about this and other fragment methods can been found here.
If you are adding click listeners in Dialog to your buttons, you need to add onclick for your new buttons objects create after onConfigurationChanged.
setting on click listener in xml is good practice for removing problem like this:
so set on click in xml like this :
<Button
android:id="#+id/addnote"
android:onClick="closeDialog"
/>
now in activity call onclick where you want
public void closeDialog(View view) {
dialogObject.dismiss();
}
after using on click in xml no need to call setOnClickListener
In my Android application, I want an EditText with android:editable="false" but the cursor blinking. The cursor blinking seems doesn't work after "editable" is set to false.
I just want to use my own Keyboard widget(not the system's soft keyboard), and keep the cursor blinking.
Is there any idea to make that possible?
Maybe try leaving out the xml attribute android:editable entirely and then try the following in combination to
keep the cursor blinking and prevent touch events from popping up a native IME(keyboard)..
/*customized edittext class
* for being typed in by private-to-your-app custom keyboard.
* borrowed from poster at http://stackoverflow.com/questions/4131448/android-how-to-turn-off-ime-for-an-edittext
*/
public class EditTextEx extends EditText {
public EditTextEx(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onCheckIsTextEditor() {
return false; //for some reason False leads to cursor never blinking or being visible even if setCursorVisible(true) was called in code.
}
}
Step 2
change the above method to say return true;
Step 3
Add another method to above class.
#Override
public boolean isTextSelectable(){
return true;
}
Step 4
In the other location where the instance of this class has been instantiated and called viewB I added a new touch event handler
viewB.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
viewB.setCursorVisible(true);
return false;
}
});
Step 5 Check to make sure XML and or EditText instantiation code declares IME/keyboard type to be 'none'. I didnt confirm relevance, but Im also using the focusable attributes below.
<questionably.maybe.too.longofa.packagename.EditTextEx
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:focusable="true"
android:focusableInTouchMode="true"
android:inputType="none">
Sorry for so many xml attributes. My code uses them all, testing in 4.2.1, and has results.
Hope this helps.
You can use either the xml attribute
android:cursorVisible="false"
or the java function
setCursorVisible(false).
it will work
Just Adding this method for anyone looking for and answer. I have tried many methods but only this one worked from me.
public static void disableSoftKeyboard(final EditText v) {
if (Build.VERSION.SDK_INT >= 11) {
v.setRawInputType(InputType.TYPE_CLASS_TEXT);
v.setTextIsSelectable(true);
} else {
v.setRawInputType(InputType.TYPE_NULL);
v.setFocusable(true);
}
}
I called the following from onCreate(), but this affects all EditTexts.
private void hideKeyboard ()
{
getWindow ().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
getWindow ().setFlags (WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
}
To all,
I am trying to get a simple NumberPicker to work in a AlertDialog. The problem is that whenever I increase/decrease the value in the numberpicker, the keyboard activates.
There are many posts describing this problem, but none of the suggestions work.
I have tried:
android:configChanges="keyboard|keyboardHidden"
And
inputManager.hideSoftInputFromWindow(currentView.getWindowToken(), 0);
And
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
I have tried calling these functions before and after initialization (dialog.show ()), on keypress events (using listeners obviously), etc. but no luck so far.
The complete code:
popup.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/myNumber"
android:configChanges="keyboard|keyboardHidden"
/>
</RelativeLayout>
And the calling function:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
} });
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
} });
View view = getLayoutInflater().inflate(R.layout.popup, null);
builder.setView (view);
final AlertDialog dialog = builder.create ();
NumberPicker picker = (NumberPicker) view.findViewById(R.id.myNumber);
picker.setMinValue(0);
picker.setMaxValue(999);
dialog.getWindow().
setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
dialog.show();
Any help appreciated
Barry
Actually, although the solution above works perfectly, there is an easier way.
picker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
This is all that is needed. Anyway, thanks for the replies!!!! :-)
Since there is no access to NumberPicker buttons, it's "impossible" to do.
I made fast dirty hack to deal with it.
First add focus eater to layout, in this case Button with 0 size:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/myNumber"
android:configChanges="keyboard|keyboardHidden"
/>
<Button
android:id="#+id/myBtn"
android:layout_width="0dp"
android:layout_height="0dp"
/>
</RelativeLayout>
We need to catch event of clicking on incement/decrement buttons, I chose OnValueChangedListener, couldn't find something better.
EditText edit = null;
try {
final Field[] fields = picker.getClass().getDeclaredFields();
for (Field f : fields) {
if (EditText.class.equals(f.getType())) {
f.setAccessible(true);
edit = (EditText) f.get(picker);
}
}
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (edit != null) {
final EditText finalEdit = edit;
final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
picker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
dialog.findViewById(R.id.myBtn).requestFocusFromTouch();
imm.hideSoftInputFromWindow(finalEdit.getWindowToken(), 0);
}
});
}
This is not recommended solution. I hope someone would find something better.
Use only for educational purpose ;-)
the android:configChanges attribute belongs in your Manifest.xml file, not the layout. But if you are hiding the keyboard from there, you are probably best of using
android:windowSoftInputMode="stateAlwaysHidden"
You should also try to use getWindow() on your Activity rather than just the Dialog and see if that helps. This is probably the best solution as the first one (hiding from the manifest) will keep the keyboard hidden throughout the entire Activity.
XML:
<NumberPicker
...
android:descendantFocusability="blocksDescendants" />
so I tried android:selectAllOnFocus and of course I'm using android:hint.
The app loads, requestFocus triggers and the full text is selected.
The problem is that when I click in the EditText the selection is lost.
I've already read:
Select all text inside EditText when it gets focus
For some reason, it worked (on Jelly Bean) only if I posted it with a Handler:
new Handler().post(new Runnable() {
#Override
public void run() {
paidView.selectAll();
}
});
Set the selection in an View.OnClickListener like so:
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editText.setSelection(0, editText.getText().length() - 1);
}
}
Set the selection in an View.OnClickListener like so: (with the 0 and text length opposite to the previously approved response) - this will ensure that when the user starts typing the content will be overridden.
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editText.setSelection(editText.getText().length() - 1, 0);
}
}
I realize this is an old post, but I had this same problem. For me, the reasoning was that I like to move the keyboard out of the way (dismiss it) to get my bearings (or hit buttons to add or remove rows of data) and when i touched back on the EditText I was previously editing, it was annoying to have the keyboard pop back up and the text un-select, forcing me to either work to get the cursor to where I wanted to start deleting, or touch another EditText and then touch back on the original to re-select everything. I just want to have the keyboard pop back up and have the text selected and ready to overwrite whenever I go to that EditText.
There are easy solutions to this:
1) Long tap does this for you on most occasions.
2) If you're already using setSelectAllOnFocus(true), you can just throw a simple clearFocus() and requestFocus() in your onClick listener:
etMyEditText.setSelectAllOnFocus(true);
etMyEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.clearFocus();
view.requestFocus();
}
});
This way the EditText has everything selected when you tap on it, regardless of soft keyboard status.
Additional bonus:
Add android:windowSoftInputMode="adjustPan" inside your <activity .../> tag in your AndroidManifest.xml file to force the selected EditText to stay in sight when the soft keyboard pops up.
try This
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editText.selectAll();
//or this.selectAll();
}
To select all the text.
Do the code below after you did findViewById and you are good to go:
edtProductPrice.setSelectAllOnFocus(true);
edtProductPrice.requestFocus();
edtProductPrice.selectAll();
I am very new to developping Android application and I am facing a
difficulty.
What I want to do is to use a specific keyboard when I click on an
EditText. So far, I have found the Keyboard and KeyboardView
classes but I haven't succeeded to do what I want yet.
Here is the description of where I am :
I have described my keyboard in a XML file,
I create a "KeyboardView" object,
I initialize it with clavier=new KeyboardView(activité,
(AttributeSet)findViewById(R.xml.clavier_numerique));
but I don't know how to replace the standard keyboard with this
customized keyboard.
Am I doing something wrong? What else should I do?
Thanks in advance for the time you will spend trying to help me.
You should use something like this:
//retrieve the keyboard view from xml
kbdV= (KeyboardView) findViewById(R.id.kbd);
//set the keyboard layout to the layout you defined in res/xml/keyboard_layout.xml
kbdV.setKeyboard(new Keyboard(this,R.xml.keyboard_layout)); //defines the keyboard layout
//add a keyboard action listener
kbdV.setOnKeyboardActionListener(new KeyboardView.OnKeyboardActionListener(){
public void onKey(int primaryCode, int[] keyCodes) {
handlePress(primaryCode, keyCodes); // callback to handle keypresses
}
public void onPress(int primaryCode) {}
public void onRelease(int primaryCode) {}
public void onText(CharSequence text) {}
public void swipeDown() {}
public void swipeLeft() {}
public void swipeRight() {}
public void swipeUp() {}
});
with a layout xml file similar to this :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- your widgets here -->
<KeyboardView android:id="#+id/kbd" android:layout_width="fill_parent" android:layout_height="wrap_content"/>
</LinearLayout>
At first you should decide what you want from keyboard:
if you just want to change to numbers you can do that by the first answer from Macarse
if you want a complete customized keyboard you should use Keyboard and KeyboardView classes by a second project
You need to specify an inputType in the xml:
<EditText android:inputType="textUri"/>
or from the code doing:
EditText input;
input.setInputType(InputType.TYPE_CLASS_NUMBER);
You can read the available inputTypes here.
When you initialize it with clavier=new KeyboardView(activity,
(AttributeSet)findViewById(R.xml.clavier_numerique),EditText edit);
You can transfer the EditText object in. And hide the standard keyboard,show the customized KeyboardView like this.
public void showKeyboard() {
if (edit != null) {
InputMethodManager imm = (InputMethodManager)mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edit.getWindowToken(), 0);
}
keyboardView.setVisibility(View.VISIBLE);
keyboardView.setEnabled(true);
}