Android - Unable to add window - android

I am using AwesomeValidation to validate all forms in my app.
It works well for every other form other than a form which has a PopupWindow when user clicks a TextView.
When I click on the PopupWindow's button which validates the form inside it, it does nothing. But after I input anything inside the EditText, it shows
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#15f1d142 is not valid; is your activity running?
Here's my code for the popup window :
View.OnClickListener phoneReinputHandler = new View.OnClickListener() {
public void onClick(View arg0) {
/*Intent intent = new Intent(SignupStepTwoActivity.this, PopupHandphone.class);
backDim = (RelativeLayout) findViewById(R.id.bac_dim_layout);
//backDim.setVisibility(View.VISIBLE);
startActivity(intent);*/
mainLayout = (RelativeLayout)findViewById(R.id.activity_signup_step_two_mainLayout);
backDim = (RelativeLayout)findViewById(R.id.bac_dim_layout);
backDim.setVisibility(View.VISIBLE);
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//View popupLayoutInflater = inflater.inflate(R.layout.popup_handphone, mainLayout);
PopupWindow pw = new PopupWindow(
inflater.inflate(R.layout.popup_handphone, null, false),
(int)(width * .8),
(int)(height*.35),
true);
//pw.setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
pw.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
pw.setOutsideTouchable(true);
RelativeLayout popupFunctionalitiesWrapper = (RelativeLayout)pw.getContentView().findViewById(R.id.popup_handphone_functionalities);
//popupFunctionalitiesWrapper.setGravity(Gravity.CENTER);
int popupFunctionalitiesWrapperWidth = layoutResize.width(70);
RelativeLayout.LayoutParams popupFunctionalitiesWrapperParams = (RelativeLayout.LayoutParams)popupFunctionalitiesWrapper.getLayoutParams();
popupFunctionalitiesWrapperParams.width = popupFunctionalitiesWrapperWidth;
popupFunctionalitiesWrapperParams.addRule(Gravity.CENTER);
popupFunctionalitiesWrapper.setLayoutParams(popupFunctionalitiesWrapperParams);
userPhonePopup = (EditText)pw.getContentView().findViewById((R.id.popup_handphone_phoneNumber));
mAwesomeValidation.addValidation(userPhonePopup, Patterns.PHONE, "Phone number must not be empty");
userPhoneCfmPopup = (EditText)pw.getContentView().findViewById((R.id.popup_handphone_phoneNumberConfirm));
Button buttonPhoneCodeResend = (Button)pw.getContentView().findViewById(R.id.popup_handphone_phoneNumberButton);
buttonPhoneCodeResend.setOnClickListener(new View.OnClickListener() {
AwesomeValidation resendPhoneValidation = new AwesomeValidation(ValidationStyle.COLORATION);
#Override
public void onClick(View v) {
Context context = v.getContext();
if(!((Activity) context).isFinishing())
{
if (!userPhonePopup.getText().toString().equals(userPhoneCfmPopup.getText().toString())) {
resendPhoneValidation.addValidation(userPhoneCfmPopup, "/^" + userPhonePopup.getText().toString() + "$/", "Nomor handphone harus sama");
}
resendPhoneValidation.validate();
}
}
});
pw.showAtLocation(mainLayout, Gravity.CENTER, 0, 0);
pw.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
backDim.setVisibility(View.GONE);
}
});
}
};
A problem with Context?

Related

Undo Button for a WordSearch app

I'm new to android and I'm having a hard time finding solutions to my problem on my app.
My app is a wordsearch game that uses tapping on the tiles as an input. This is the code for the onClick() of the dynamic textviews on the tablelayout:
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
w.setVisibility(View.VISIBLE);
//change the color of tapped textview
text.setTextColor(Color.WHITE);
text.setBackgroundColor(Color.parseColor(mColors[randomNum]));
String b = text.getText().toString();
uTxt.setText(""+uTxt.getText().toString() + b);
//check if answer is in the word grid
if(checkAns(uTxt, list))
{
w.setVisibility(View.GONE);
wC.setText(String.valueOf(Integer.parseInt(wC.getText()+"")-1));
if(Integer.parseInt(wC.getText()+"") == 0){
int newM = minutes*60 + seconds;
dataHelper.insertData(pNameC.getText().toString(), newM, currentDateandTime, Category.leve);
t.cancel();
Context mContext = getApplicationContext();
Activity mActivity = GameScreen.this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
// Inflate the custom layout/view
View customView = inflater.inflate(R.layout.gameover,null);
// Initialize a new instance of popup window
PopupWindow mPopupWindow = new PopupWindow(
customView,
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
Typeface font = Typeface.createFromAsset(getAssets(), "raw2.ttf");
TextView cattxt = (TextView)customView.findViewById(R.id.catTxt);
String ctg = ti.getText().toString();
cattxt.setTypeface(font);
cattxt.setText(ctg);
Button yesB = (Button) customView.findViewById(R.id.maglaro2);
yesB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(GameScreen.this, Category.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
GameScreen.this.finish();
}
});
Button noB = (Button) customView.findViewById(R.id.hindi);
noB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(GameScreen.this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
GameScreen.this.finish();
}
});
mPopupWindow.showAtLocation(table, Gravity.CENTER,0,0);
}
uTxt.setText("");
}
}
});
Now my problem is I want an UNDO Button that will delete the last character on the uTxt and will change back the color of the last touched textView
Does anyone have any ideas on how to do that?
If yes leave a comment, answer, or suggestion below. TIA!
Typical solution for this problem is the usage of the command pattern (excellent for undo redo functionality).
See https://en.wikipedia.org/wiki/Command_pattern

Android - Popup window is not closing

I want to close the popup window when I click a button, but it seems dismiss function doesn't work and the window is not closing. What did I wrong?
(I'm a beginner, so codes might be 'weird'. Please understand...)
public class AlarmPopup extends Activity {
private PopupWindow popup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onShowPopup();
}
public void onShowPopup(){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.alarm_popup, null, false);
final PopupWindow popup = new PopupWindow(view, 400, 300, true);
setContentView(R.layout.alarm_popup);
view.findViewById(R.id.button).post(new Runnable() {
#Override
public void run() {
popup.showAtLocation(view, Gravity.CENTER, 0, 0);
}
});
findViewById(R.id.button).setOnClickListener(mClickListener);
}
Button.OnClickListener mClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) { // dismiss and stop the alarm function on other class
Intent i = new Intent(AlarmPopup.this, AlarmService.class);
stopService(i); // this function is working...
popup.dismiss();
}
};
}
You have declared popup as global and inside your onShowPopup you are creating new object for popup so that local popup will never be accessible from listener so make the changes as below:
public void onShowPopup(){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.alarm_popup, null, false);
popup = new PopupWindow(view, 400, 300, true);
setContentView(R.layout.alarm_popup);
view.findViewById(R.id.button).post(new Runnable() {
#Override
public void run() {
popup.showAtLocation(view, Gravity.CENTER, 0, 0);
}
});
view.findViewById(R.id.button).setOnClickListener(mClickListener);
}
Popup variable that you are using to dismiss your popup window has not been initialized in the code that you have posted. Your final variable that you have created inside method is local and will not be accessible outside that method.
So initialize your variable or use same variable inside method too.

Implement emojis in android keyboard with popupwindow

I've developed a keyboard and now i need to add emojis to it , from other questions i've realized the best way is with popupwindow,
Here's what i've done:
case -102:
LayoutInflater layoutInflater
= (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.emoji_view, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
popupWindow.showAsDropDown(getWindow().getOwnerActivity().getCurrentFocus(),50, -30);
Unfortunatly this doesn't work , showAsDropDown needs a view as its first var , and if the keyboard is in another app i don't have a view to give him...
Is there a way to fix that ?
or am i going about it all wrong and there is a better way...
all help will be appreciated!
Given that you are using the official SoftKeyBoard implementation as a template for your keyboard:
//Cut some pieces of the code for clarity
case -102:
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.emoji_view, null);
PopupWindow popupWindow = new PopupWindow(popupView, MATCH_PARENT, MATCH_PARENT);
popupWindow.showAsDropDown(mInputView);
Use the view that you have inflated for your keyboard, in the offical SoftKeyBoard and the snippet above it is called mInputView.
hi i have done same things. I have made one custom keyboard in android.
EmoticonsPagerAdapter emojiAdapter;
/**
* Defining all components of emoticons keyboard
*/
private void enablePopUpView() {
final ViewPager pager = (ViewPager) popUpView
.findViewById(R.id.emoticons_pager);
pager.setOffscreenPageLimit(3);
final ArrayList<EmojiItem> paths = EmojiUtil.getInstance(acitiviy)
.getAllEmojis();
final ArrayList<EmojiItem>[] groups = new ArrayList[5];
for (EmojiItem emoji : paths) {
if (groups[emoji.emojiGroup] == null) {
groups[emoji.emojiGroup] = new ArrayList<EmojiItem>();
}
groups[emoji.emojiGroup].add(emoji);
}
final ArrayList<EmojiItem> history = new ArrayList<EmojiItem>();
ArrayList<Integer> historyIds = SettingsUtil.getHistoryItems(acitiviy);
for (Integer his : historyIds) {
for (EmojiItem emoji : paths) {
if (emoji.id == his) {
history.add(emoji);
break;
}
}
}
history.add(paths.get(0));
final KeyClickListener onEmojiClick = new KeyClickListener() {
#Override
public void keyClickedIndex(EmojiItem index) {
int cursorPosition = editMessage.getSelectionStart();
editMessage.getText().insert(cursorPosition, index.emojiText);
try {
editMessage.getText().setSpan(
new ImageSpan(index.emojiDrawable), cursorPosition,
cursorPosition + 1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} catch (Exception e) {
}
if (history.get(0) != index)
history.add(0, index);
SettingsUtil.setHistoryItems(acitiviy, history);
emojiAdapter.notifyDataSetChanged();
pager.setAdapter(emojiAdapter);
}
};
((ImageButton) popUpView.findViewById(R.id.emoji2))
.setImageDrawable(groups[0].get(0).emojiDrawable);
((ImageButton) popUpView.findViewById(R.id.emoji3))
.setImageDrawable(groups[1].get(0).emojiDrawable);
((ImageButton) popUpView.findViewById(R.id.emoji4))
.setImageDrawable(groups[2].get(0).emojiDrawable);
((ImageButton) popUpView.findViewById(R.id.emoji5))
.setImageDrawable(groups[3].get(0).emojiDrawable);
((ImageButton) popUpView.findViewById(R.id.emoji6))
.setImageDrawable(groups[4].get(0).emojiDrawable);
popUpView.findViewById(R.id.emoji1).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
emojiAdapter.emojis = history;
emojiAdapter.notifyDataSetChanged();
pager.setAdapter(emojiAdapter);
}
});
popUpView.findViewById(R.id.emoji2).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
emojiAdapter.emojis = groups[0];
emojiAdapter.notifyDataSetChanged();
pager.setAdapter(emojiAdapter);
}
});
popUpView.findViewById(R.id.emoji3).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
emojiAdapter.emojis = groups[1];
emojiAdapter.notifyDataSetChanged();
pager.setAdapter(emojiAdapter);
}
});
popUpView.findViewById(R.id.emoji4).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
emojiAdapter.emojis = groups[2];
emojiAdapter.notifyDataSetChanged();
pager.setAdapter(emojiAdapter);
}
});
popUpView.findViewById(R.id.emoji5).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
emojiAdapter.emojis = groups[3];
emojiAdapter.notifyDataSetChanged();
pager.setAdapter(emojiAdapter);
}
});
popUpView.findViewById(R.id.emoji6).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
emojiAdapter.emojis = groups[4];
emojiAdapter.notifyDataSetChanged();
pager.setAdapter(emojiAdapter);
}
});
emojiAdapter = new EmoticonsPagerAdapter(acitiviy, groups[0],
onEmojiClick);
pager.setAdapter(emojiAdapter);
// Creating a pop window for emoticons keyboard
popupWindow = new PopupWindow(popUpView, LayoutParams.MATCH_PARENT,
(int) keyboardHeight, false);
View backSpace = (View) popUpView.findViewById(R.id.imageBackspace);
backSpace.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0,
0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
editMessage.dispatchKeyEvent(event);
}
});
popupWindow.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss() {
emoticonsCover.setVisibility(LinearLayout.GONE);
}
});
ViewPager pagerStickers = (ViewPager) popUpView
.findViewById(R.id.stickers_pager);
pagerStickers.setOffscreenPageLimit(3);
}
private void showKeyboardPopup(View root, boolean attaches) {
if (!popupWindow.isShowing()) {
popupWindow.setHeight((int) (keyboardHeight));
if (isKeyBoardVisible) {
imageEmoji.setImageResource(R.drawable.emoji_kbd);
emoticonsCover.setVisibility(LinearLayout.GONE);
} else {
imageEmoji.setImageResource(R.drawable.ic_down);
emoticonsCover.setVisibility(LinearLayout.VISIBLE);
}
try {
popupWindow.showAtLocation(root, Gravity.BOTTOM, 0, 0);
} catch (Exception e) {
}
} else {
imageEmoji.setImageResource(R.drawable.emoji_btn_normal);
popupWindow.dismiss();
return;
}
imageAttaches.setBackgroundColor(attaches ? 0xFF808080 : 0x00000000);
imageEmojis.setBackgroundColor(attaches ? 0x00000000 : 0xFF808080);
imageStickers.setBackgroundColor(0x00000000);
layoutEmojis.setVisibility(attaches ? View.GONE : View.VISIBLE);
layoutStickers.setVisibility(View.GONE);
}
Please checkout for more details click here.
Thanks hope this will help you.It is bit old but you can try it.
you can refer this github link for complete code
EmojiIcon

Unable to add Window, Token is not valid error when clicked on a Spinner

I have an android application when clicked on an option from a side bar it goes to a fragment, and then into another fragment which has clickable radio buttons. When clicked on these it will create a popup window with some text fields in it.
Basically this is how the flow goes,
Activity --> Fragment 1 --> Fragment 2 --> PopupWindow
And i have a spinner on this PopupWindow, but when i click on it to select a value it throws the following exception. I don't understand why this happen.
Process: com.informaticsint.claimassistant, PID: 5045
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#945936c is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:849)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:337)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.widget.PopupWindow.invokePopup(PopupWindow.java:1329)
at android.widget.PopupWindow.showAsDropDown(PopupWindow.java:1155)
at android.widget.ListPopupWindow.show(ListPopupWindow.java:791)
at android.widget.Spinner$DropdownPopup.show(Spinner.java:1366)
at android.widget.Spinner.performClick(Spinner.java:828)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
This is the Spinner code that cause the problem. Which is in the below mentioned AssignmentDetailsActivity class, showDamagedItemEntryPopup() method
statusSpinner = (Spinner)popupView.findViewById(R.id.popup_status_spinner);
ArrayAdapter<String> statusSpinnerArrayAdapter = new ArrayAdapter<String>(AssignmentDetailsActivity.this, android.R.layout.simple_spinner_item, statusSpinnerArray);
statusSpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
statusSpinner.setAdapter(statusSpinnerArrayAdapter);
This is my method that creates the popup which is in my AssignmentDetailsActivity class
public void showDamagedItemEntryPopup(RadioButton radioButton, View view){
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.component_selection_popup, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
// Set popup Animation style
popupWindow.setAnimationStyle(R.style.popupAnimation);
Button buttonClose = (Button)popupView.findViewById(R.id.close_add_component_btn);
// Close button damaged item popop window
buttonClose.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
originalAmount = (EditText)popupView.findViewById(R.id.popup_add_component_original_amount);
customerContribution = (EditText)popupView.findViewById(R.id.popup_percentage);
quantity = (EditText)popupView.findViewById(R.id.popup_quantity);
finalAmount = (EditText)popupView.findViewById(R.id.popup_add_component_final_amount);
remarks = (EditText)popupView.findViewById(R.id.popup_add_component_remarks);
// Item Spinner
itemSpinnerArray = new ArrayList<String>();
itemSpinnerArray.add("Select Item");
// Status Spinner
ArrayList<String> statusSpinnerArray = new ArrayList<String>();
statusSpinnerArray.add("FDR");
statusSpinnerArray.add("DR");
statusSpinnerArray.add("SP");
damageComponenetAutoCompleteTextview = (AutoCompleteTextView) popupView.findViewById(R.id.popup_damage_component_item);
damageComponenetAutoCompleteTextview.requestFocus();
ArrayAdapter<String> itemSpinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, itemSpinnerArray);
damageComponenetAutoCompleteTextview.setThreshold(1);
damageComponenetAutoCompleteTextview.setAdapter(itemSpinnerArrayAdapter);
damageComponenetAutoCompleteTextview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
itemSpinnerValue = (String) parent.getItemAtPosition(position);
Log.d("SK-->", "----------------------------------------------------------");
Log.d("SK-->","itemSpinnerValue: " + itemSpinnerValue);
}
});
statusSpinner = (Spinner)popupView.findViewById(R.id.popup_status_spinner);
ArrayAdapter<String> statusSpinnerArrayAdapter = new ArrayAdapter<String>(AssignmentDetailsActivity.this, android.R.layout.simple_spinner_item, statusSpinnerArray);
statusSpinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
statusSpinner.setAdapter(statusSpinnerArrayAdapter);
//Creating a text Watcher
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
//here, after we introduced something in the EditText we get the string from it
//String answerString = originalAmount.getText().toString();
if (originalAmount.getText().toString().trim().equals("") || customerContribution.getText().toString().trim().equals("")
|| quantity.getText().toString().trim().equals("")) {
// Error , one or more editText are empty
}
else
{
calculateFinalAmount();
}
//and now we make a Toast
//modify "yourActivity.this" with your activity name .this
//Toast.makeText(yourActivity.this,"The string from EditText is: "+answerString,0).show();
}
};
// Adding Text Watcher to our text boxes
originalAmount.addTextChangedListener(textWatcher);
customerContribution.addTextChangedListener(textWatcher);
quantity.addTextChangedListener(textWatcher);
// Show the popup
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
}
public void onSaveItem(View view) {
statusSpinnerValue = (String) statusSpinner.getItemAtPosition(statusSpinner.getSelectedItemPosition());
statusSpinnerValue = "ABC";
itemSpinnerValue = "TEST ITEM";
originalAmount.setText("50");
customerContribution.setText("25");
quantity.setText("1");
if(itemSpinnerValue.matches("Select Item") ||itemSpinnerValue.matches("") || statusSpinnerValue.matches("") || originalAmount.getText().toString().matches("") || customerContribution.getText().toString().matches("") ||
quantity.getText().toString().matches("")){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("ERROR!");
builder.setMessage("Please Fill the Required Fields.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
else{
Log.e("TEST", "Check Passed");
Date date = new Date();
if(mDbHandler.itemAlreadyExist(reportID,"item_name", itemSpinnerValue, "DamageComponent") == false){
mDbHandler.addDamageComponent(reportID, itemSpinnerValue, statusSpinnerValue, originalAmount.getText().toString(), Double.parseDouble(customerContribution.getText().toString()),
Integer.parseInt(quantity.getText().toString()), finalAmount.getText().toString(), remarks.getText().toString());
mDbHandler.updateReport(reportID, date.toString(), "time_last_modified");
Toast.makeText(this,"Component Successfully Added",Toast.LENGTH_SHORT).show();
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("ERROR!");
builder.setMessage("Item Already Exist.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
mDbHandler.close();
}
}
Spent 2 days for exactly the same problem :(
The only workaround I find is to use spinner in dialog mode
android:spinnerMode="dialog"
Glad to help you again, Have a look at this question's answers. You are showing popup too early so that you need to delay the run like this
view.post(new Runnable() {
public void run() {
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
}
});
UPDATE :
OR try
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
}
}, 1000); //Delay one second

multiple popups in android

I have two Linear Layouts in single activity .
I want to display custom popups on each of them when clicked.
When I click on first layout, popup apperas,then on clicking on 2nd layout ,both popups are displayed. how can i have only single popup displayed at a time?
this is my code
workLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater layoutInflater=
(LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate
(R.layout.activity_your_places__work__popup, null);
updateTextView = (TextView)
popupView.findViewById(R.id.UpdateTextView);
updateTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Your_Places2Activity.this,
UpdateWorkAddressActivity.class);
startActivity(i);
}
});
deleteTextView = (TextView)
popupView.findViewById(R.id.DeleteTextView);
deleteTextView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
//code to delete address
}
});
popupWindowWork = new PopupWindow(
popupView,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
//dismiss other popup if is showing
if(popupWindowHome.isShowing())
{
popupWindowHome.dismiss();}
//display popup
popupWindowWork.showAsDropDown(workLinearLayout, 0, -70);
}
});
i have done same thing on other linear layout
popupWindowWork = new PopupWindow(
popupView,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
if(popupWindowHome.isShowing())
{
popupWindowHome.dismiss();
}
in this line, you are dismissing the popupWindowHome dialog if popupWindowHome is showing, with popupWindowHome being the NEW dialog. Move the if statement before the constructor call.
if(popupWindowHome != null && popupWindowHome.isShowing())
{
popupWindowHome.dismiss();
}
popupWindowWork = new PopupWindow(
popupView,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);

Categories

Resources