NumberPicker in AlertDialog always activates keyboard. How to disable this? - android

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" />

Related

Unable to maintain the state of a custom dialog button when screen orientation changes

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

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();

How to create a guided tour for an android application

A couple of months ago I bought myself an HTC ONE X. I admired they way they guide the user in taking his first steps in the phone with interactive widgets and help functions.
I would like to add this kind of functionality to Rogerthat, the app we are building, but I wonder if there are tools / libraries that can help me achieve this?
Roman Nurik put together a library called "Wizard Pager" to do this sort of thing. It could likely be used to do what you're asking.
https://plus.google.com/113735310430199015092/posts/6cVymZvn3f4
http://code.google.com/p/romannurik-code/source/browse/misc/wizardpager
Update:
I think this might also be helpful to you. It's similar to the tour shown when first running a stock Android rom in ICS+.
The library can be used in any version of Android:
https://github.com/Espiandev/ShowcaseView
If you want consecutive showcases you can look at this expansio:
https://github.com/blundell/ShowcaseViewExample
I did a guided tour for my app that allows the user to navigate through 4 note pages ans see the instructions. Here's the code:
public static void tour(final Context context, final String title, final int pageNumber,
final Drawable icon, final String[] pageMessage, final int[] layouts, final ViewGroup root) {
Builder tourDialog = new AlertDialog.Builder(context);
int nPage = 0;
if (pageMessage!=null){
tourDialog.setMessage(pageMessage[pageNumber]);
nPage = pageMessage.length;
}
if (layouts!=null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View layout1 = inflater.inflate(layouts[pageNumber], root);
tourDialog.setView(layout1);
//tourDialog.setView(views[pageNumber]);
nPage = layouts.length;
}
tourDialog.setTitle(title+" (page "+(pageNumber+1)+"/"+nPage+")");
tourDialog.setPositiveButton("Prev",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
tour(context, title, pageNumber-1, icon, pageMessage,layouts, root);
return;
}
});
tourDialog.setNeutralButton("Next",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
tour(context, title, pageNumber+1, icon, pageMessage,layouts, root);
return;
}
});
tourDialog.setNegativeButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
return;
}
});
if (icon!=null)
tourDialog.setIcon(icon);
AlertDialog dialog = tourDialog.create();
dialog.show();
if (pageNumber==0)
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
else if (pageNumber==nPage-1){
dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setEnabled(false);
}
}
Example of usage:
int[] layout = {R.layout.note1, R.layout.note2, R.layout.note3, R.layout.note4}; //resource id of each page's layout
tour(context, "Notes ", 0,getResources().getDrawable(R.drawable.gmpte_logo_25px),null, layout, (ViewGroup) findViewById(R.id.root));
and an example of note page layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/root"
android:padding="10dip">
<TextView android:id="#+id/text_before"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:textSize="16dp"
android:text="#string/note1_before_text"
android:layout_marginTop="10dp"/>
<ImageView android:id="#+id/image"
android:contentDescription="#string/desc"
android:src="#drawable/mylocation_blue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/text_before"
/>
<TextView
android:id="#+id/text_after"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/text_before"
android:layout_below="#+id/image"
android:text="#string/note1_after_text"
android:textColor="#FFF"
android:textSize="16dp" />
</RelativeLayout>
You need to write your own layout for each note page, but use the same id (android:id="#+id/root") for the root layout in each page.
The Showcase View Library is definitely what you want:
Use a ViewPager and a fragment to show your help screens. You'll find plenty information about that.
I wrote little library
That contains a simple component for making ​​a app tour.
It`s very restricted to my case but maybe could be your case .
Single LessonCardView Showed onstartactivity for the first time
or on button click
Any criticism ,help or advice will be appreciated. thanks
https://github.com/dnocode/DnoLib
You can try TourGuide http://worker8.github.io/TourGuide
It's fairly up-to-date (uses Kotlin 1.2) and works pretty nicely.
Most of the alternatives I've checked recently (in 2021), are either not working or buggy.
TourGuide is not perfect (it's been 3 years since it's last commit), and the maintainer doesn't seem to respond to PRs or issues.

Android: EditText in Dialog doesn't pull up soft keyboard

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);

How do I get edittext value from a custom AlertDialog where retrieval of values is not in the onClick?

What I am trying to do is to create a custom dialog that overrides an AlertDialog.
What it is supposed to do is get some text (at least 2 strings) and then for each of those strings it is supposed to be able to get more information, but I want to do this in custom dialogs.
So what is supposed to happen is a user can enter 2 people in an activity screen, and then for the first person, you get a custom dialog and that person can enter three words, and then it jumps to the next custom dialog (exact same layout I am inflating) and the second person can enter some words.
This is my xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinLay_Enter_Words"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/TextView_AddPlayerWord_Instruction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/help_text_size"
android:textStyle="bold"></TextView>
<EditText
android:id="#+id/EditText_Word1"
android:layout_height="wrap_content"
android:maxLength="20"
android:layout_width="match_parent"
android:maxLines="1"></EditText>
<EditText
android:id="#+id/EditText_Word2"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:maxLines="1"></EditText>
<EditText
android:id="#+id/EditText_Word3"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:maxLines="1"></EditText>
</LinearLayout>
And this is part of the code:
protected Dialog onCreateDialog(int id) {
switch (id) {
case NOUN_INPUT_DIALOG_ID:
Dialog returnedDialog = initWordDialog();
return(returnedDialog);
}
return null;
}
It calls initWordDialog():
private Dialog initWordDialog() {
LayoutInflater inflater = LayoutInflater.from(this); //(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogLayout = inflater.inflate(R.layout.word_entry_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
...
TextView v1 = (TextView) dialogLayout.findViewById(R.id.TextView_AddPlayerWord_Instruction);
...
v1.setText("SomeText");
builder.setView(dialogLayout);
builder.setTitle(R.string.enter_word_title);
builder.setPositiveButton("Next", onNextSubmit);
AlertDialog wordBuilderDialog = builder.create();
return wordBuilderDialog;
}
I think what I am trying to find has been discussed to some degree here:
Value of EditText in Custom Dialog
Android - Custom Dialog - Can't get text from EditText
How to add two edit text fields in an alert dialog
The problem, I believe, lies here, where all of the examples everyone has their onClick in the same function as their onCreate. My stuff was a bit more complicated and I wanted to separate out the functions; however, as a result, I am now unable to access any of the EditText variables.
Here is my onClick implementation:
private DialogInterface.OnClickListener onNextSubmit = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (setPlayerWords()) {
...
}
};
The part that matters is I don't even get to the part where I'm accessing the edittexts until setPlayerWords is called, and this is where it is failing:
public boolean setPlayerWords() {
PMGamePlay pmObj = (PMGamePlay) getApplicationContext();
String[] playerWords = new String[pmObj.numberOfWordsPlayersGetToInput()];
//LayoutInflater inflater = LayoutInflater.from(this);
//View dialogLayout2 = inflater.inflate(R.layout.word_entry_dialog, null);
//setContentView(R.layout.word_entry_dialog);
final LinearLayout myLayout = (LinearLayout) findViewById(R.id.LinLay_Enter_Words);
final EditText w0 = (EditText) myLayout.findViewById(R.id.EditText_Word1);
final EditText w1 = (EditText) myLayout.findViewById(R.id.EditText_Word2);
final EditText w2 = (EditText) myLayout.findViewById(R.id.EditText_Word3);
String test = w0.getText().toString();
playerWords[0] = w0.getText().toString();
playerWords[1] = w1.getText().toString();
playerWords[2] = w2.getText().toString();
...
return true;
}
I initially tried re-inflating, but that seemed to reset and while the edittexts would not be null, they were reset to have "" in their values.
Then I tried to setContentView on my xml file, but that still gave me a null value.
Now, I just try and simply access the linearlayout, and that also returns a null value. If I just try to access the edittexts by their id directly without first going through its parent linearlayout, it also returns a null value.
At this point, I'm not sure what to do other than to cram everything that I have in these separate functions into the same single onclick, but I really don't want to do that. Is there nothing else I can do to access these edittexts?
Any help would be greatly appreciated!
Have you tried using the long version of inflate inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) ? I know that if you don't use this method there can be some issues with it grabbing layout characteristics, so might be causing the issue. For the viewgroup you should pick the parrent view for the alert and usually want attachToRoof = false;

Categories

Resources