PopUpWindow Back Key event - android

I saw many posts on this subject but couldnt find the right answer for me.
I have an activity that dims when i pop the popup window.
the back button working but only the second time i press it, the first press dismiss the popup but its not un-dim the activity because i cant catch the event from the popupwindows, the second press is catched by the activity and only then i can un-dim it.
here are my tries to accomplish this:
m_PopupWindow.setBackgroundDrawable(new BitmapDrawable());
m_PopupWindow.setOutsideTouchable(true);
View popUpWindowLaout = m_PopupWindow.getContentView();
popUpWindowLaout.setFocusableInTouchMode(true);
//first press doesnt get caught here
popUpWindowLaout.setOnKeyListener(new View.OnKeyListener()
{
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
m_ActionBar.show();
unShadeTheActivity();
m_PopupWindow.dismiss();
return true;
}
}
});
//this func will catch the second press and will work, but i want the first press will do it.
#Override
public void onBackPressed() {
if (m_PopupWindow != null)
{
m_ActionBar.show();
unShadeTheActivity();
m_PopupWindow.dismiss();
}
else
{
super.onBackPressed();
}
}

change
public void onBackPressed() {
if (m_PopupWindow != null)
{
m_ActionBar.show();
unShadeTheActivity();
m_PopupWindow.dismiss();
}
else
{
super.onBackPressed();
}
}
to
public void onBackPressed() {
super.onBackPressed();
if (m_PopupWindow != null)
{
m_ActionBar.show();
unShadeTheActivity();
m_PopupWindow.dismiss();
}
else
{
// rest of the code
// you can use finish,dismiss or call startActivity
// finish();
}
}

popupWindow.setOnShowListener(HandlePopupShowLister);
popupWindow.setOnDismissListener(HandlePopUpDismissListerner);
public static OnDismissListener HandlePopUpDismissListerner = new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
Log.i("HandlePopUpDismissListerner", "HandlePopUpDismissListerner");
CommonVariable.IsPopupOpen = false;
}
};
public static OnShowListener HandlePopupShowLister = new OnShowListener() {
// onShowListener interface.
#Override
public void onShow(DialogInterface dialog) {
Log.i("HandlePopupShowLister", "HandlePopupShowLister");
// TODO Auto-generated method stub
CommonVariable.IsPopupOpen = true;
}
};

Related

IllegalStateException: Fragment not attached to Activity when finish AsyncTask & Fragment

I am using ProgressDialog in AsyncTask. And If user Press Back Button, then AsyncTask will be cancelled, current fragment will replace by any other Fragment.
There is no issue if user is still on Application. Bu if he goes back and back speedly and at last stop application, It gives error IllegalStateException: Fragment not attached to Activity.
How to solve this ?
My Code:
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getActivity(), "", "Loading...", true,
true, new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
CancelDialog();
}
});
}
public void CancelDialog() {
new FetchData().cancel(true);
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
((FrameLayout) flMain).removeAllViews();
fm.beginTransaction().add(R.id.frame, new Home()).commit();
}
Home.java:
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == KeyEvent.ACTION_UP
&& keyCode == KeyEvent.KEYCODE_BACK) {
getView().clearFocus();
getActivity().finish();
return true;
}
return false;
}
});
}
After so many tried, lastly I have found Simple Answer: isAdded()
It will Return true if the Fragment is currently added to its Activity.
I used below code and it solved my problem.
#Override
protected void onPostExecute(Void result){
if(isAdded()){
// Code to display Data...
}
}
You should be careful when to call e.g getActivity() - your fragment might not (yet/already) be attached to an activity when you call such methods. Check out this.
Alternatively you can save the Activity instance when onAttach is called, but then you'll have to be careful what you do with that Activity instance, so that you do not make conflicting updates with another Fragment that is actually still attached.
isAdded and isDetached can be useful to check the state and avoid calling invalid methods.

onBackPressed() does not work

I'm showing up a Dialog on app-start, where you have to select a config. Since it is essential to select one config, I want to "disable" the back-button via a empty onBackPressed().
I got the following code in a DialogFragment:
public class ChangeConfigDialogFragment extends DialogFragment {
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.dialog_config_change)
.setItems(R.array.config_array,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// The 'which' argument contains the index
// position
// of the selected item
if (which == 0){
Initiation.BAUDRATE = 500;
Toast.makeText(getActivity(), "Baudrate at " + Initiation.BAUDRATE, Toast.LENGTH_LONG).show();
if (Initiation.getADK() == null){
Initiation.initiateCAN();
}
} else if (which == 1) {
Initiation.BAUDRATE = 600;
Toast.makeText(getActivity(), "Baudrate at " + Initiation.BAUDRATE, Toast.LENGTH_LONG).show();
if (Initiation.getADK() == null){
Initiation.initiateCAN();
}
} else if (which == 2) {
Initiation.BAUDRATE = 700;
Toast.makeText(getActivity(), "Baudrate at " + Initiation.BAUDRATE, Toast.LENGTH_LONG).show();
if (Initiation.getADK() == null){
Initiation.initiateCAN();
}
}
}
});
// Create the AlertDialog object and return it
return builder.create();
}
public void onBackPressed(){
Log.d(getTag(), "are you there?");
}
}
The problem is, that the onBackPressed() is never been called. Even the log message does not appear.
I tried to clean the project, but no success. Also tried to use a onKeyDown-method from some other topics here on SO. Does anyone has a clue how to solve this?
EDIT:
It works now. .setCancelable(false); worked, but I was to stupid to add it to the Dialog from which the Fragment was called. (instead added it to the builder
Thanks for all your help and time.
From your question it seems that while your dialog is open you need not to close dialog untill user can select any 1 open from dialog if i am not wrong then,so for this you need not to disable back key but you have to set this two properties for dialog.
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
OR
If you want to disable back key then use the below code,
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
return true;
}
return super.onKeyDown(keyCode, event); }
OnbackkeyPressed Requires Api Level 5 Or higher.
#Override
public void onBackPressed() {
}
Use builder.setCancelable(false)
http://developer.android.com/reference/android/app/AlertDialog.Builder.html#setCancelable(boolean)
I did not try this, but it might work if you set the OnKeyListeneron the builder like this:
builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return false;
}
}
});
Try
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
return false;
}
return super.onKeyDown(keyCode, event);
}
or
dialog.setCancelable(false);

Dismiss Custom Alert Dialog on Back button pressed of hardware in android

I am having problem on back button of hardware. In my main Activity, I have one List view(say 1). When I click on item of this List view(1), one Alert Dialog appears, in this alert dialog, there is one List view(say 2). Data of this List view(2) are being repeated when I press back button of hardware. I have also put cancel image on this alert dialog to dismiss, when I press this cancel image, data are not being repeated. I tried different methods onResume(), onPause(), onDestroy(), onRestart() to clear the array for List view(2), but nothing works. Here is my code...
case LIST_DIALOG :
LayoutInflater inflater2 = LayoutInflater.from(this);
View dialogview1 = inflater2.inflate(R.layout.listdialog, null);
AlertDialog.Builder dialogbuilder2 = new AlertDialog.Builder(this);
dialogbuilder2.setView(dialogview1);
dialogDetails = dialogbuilder2.create();
case LIST_DIALOG:
AlertDialog alertDialog1 = (AlertDialog) dialog;
// Cancel Alert Dialog
ImageView ivCancel = (ImageView) alertDialog1.findViewById(R.id.imgCancel);
ivCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dismissDialog(LIST_DIALOG);
arr2.clear();
}
});
// Friend List
showFriendList();
break;
// List view data are inserted with this function call
private void showFriendList() {
// TODO Auto-generated method stub
Request.executeMyFriendsRequestAsync(friendSession, new GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
// TODO Auto-generated method stub
// arr2 = new ArrayList<String>();
for(GraphUser user : users)
{
arr2.add(user.getName());
}
adapter2 = new ArrayAdapter<String>(getBaseContext(), R.layout.single_row, R.id.txt,arr2);
lvDialog.setAdapter(adapter2);
lvDialog.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
adapter2.notifyDataSetChanged();
itemCount = lvDialog.getCount();
Toast.makeText(getBaseContext(), "" + itemCount, 1000).show();
}
});
}
// I tried these methods, but nothing works...
#Override
public void onResume()
{
super.onResume();
ShowSavedFiles();
arr2.clear();
}
#Override
public void onPause()
{
super.onPause();
arr1.clear();
arr2.clear();
}
#Override
public void onBackPressed() {
//super.onBackPressed();
// finish your Activity
arr2.clear();
return;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
arr2.clear();
dismissDialog(LIST_DIALOG);
}
return false;
}
I'm not sure but might be adding the following code to your onKeyDown method might help out :
return super.onKeyDown(keyCode, event);

how to listen key when popup is opened

I am writing an application to animate popup window. It was working great with my code.
I want to close the popup window(i.e to slide-down it), when back button is pressed on device.
But I couldn't listen any one key from device. I used setOnKeyListener of that popup window, I didn't even get log from it.
My Code is given below:
popup_layout = layoutInflater.inflate(R.layout.popup_addchannel, null);
popupWindow = new PopupWindow(popup_layout, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
subscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Log.d(TAG,
// "Button is clicked for animation.... Visibility is"
// + subscribeButton.getVisibility());
openMenu(view);
}
});
popup_layout.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.d(TAG, "on key button click called.........");
return false;
}
});
public void openMenu(View view) {
if (!flag) {
popupWindow.setAnimationStyle(R.style.PopupWindowAnimation);
popupWindow.showAtLocation(view.findViewById(R.id.button1),
Gravity.CENTER, 0, 0);
popupWindow.setFocusable(true);
popupWindow.update();
flag = true;
} else {
popupWindow.dismiss();
popupWindow.setFocusable(false);
flag = false;
}
}
What is the problem behind this?
Shall i achieve my requirement?
Please, Guide me.
Thank you in Advance!
try this....
final PopupWindow popupWindow = new PopupWindow(popupView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,true);
...
popupWindow.getContentView().setFocusableInTouchMode(true);
popupMenu.getContentView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU &&
event.getRepeatCount() == 0 &&
event.getAction() == KeyEvent.ACTION_DOWN) {
// ... payload action here. e.g. popupMenu.dismiss();
return true;
}
return false;
}
});
The dialog has a property of cancelling the dialog on back press.
dialog.setCancelable(true);
EDIT: Check Qberticus answer on this link: Android popup window dismissal
and you can also see: Issue dismissing popup window
Yes you can use this
dialog_obj.setCancelable(true);
You should override the onKeyPressed() method of your activity as below.
#Override
public void onBackPressed() {
super.onBackPressed();
//your code to close the popup window.
popupWindow.setAnimationStyle(R.style.PopupWindowAnimation);
popupWindow.showAtLocation(view.findViewById(R.id.button1),
Gravity.CENTER, 0, 0);
opupWindow.setFocusable(true);
popupWindow.update();
flag = true;
}
popupWindow.getContentView().setOnClickListener(new OnClickListener()) {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}
});
Try this.
You can't listen a key press in popup window, but when you listen to system back key, you can override dismiss() method to intercept it.

Android - Using same dialog for multiple Views - trouble setting up

I'm having some trouble with a simple dialog i'm working on. I have three different TextView's that when they are clicked I have a dialog box pop up with only the Title and one EditText. I'm trying to make it so I use the same custom dialog for all three text views, but depending on which TextView is tapped the dialog set the new value to that TextView. Below is my code:
#Override
protected Dialog onCreateDialog(int id) {
super.onCreateDialog(id);
CustomDialogPercent dialog = null;
switch(id){
case 1:
dialog = new CustomDialogPercent(this, id);
dialog.setTitle("Shipping Percent");
dialog.show();
break;
case 2:
dialog = new CustomDialogPercent(this, id);
dialog.setTitle("Tax Percent");
dialog.show();
break;
case 3:
dialog = new CustomDialogPercent(this, id);
dialog.setTitle("Commission Percent");
dialog.show();
break;
default:
dialog = null;
}
return dialog;
}
private void registerListeners() {
shippingPercent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(1);
}
});
taxPercent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(2);
}
});
commissionPercent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(3);
}
});
}
public class CustomDialogPercent extends Dialog {
int id = 0;
public CustomDialogPercent(Context context, int id) {
super(context);
this.id = id;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_dialog);
basicDialogEntry = (EditText) findViewById(R.id.basic_dialog_entry);
basicDialogEntry.setKeyListener(DigitsKeyListener.getInstance(true,true));
}
#Override
public void onStart() {
super.onStart();
switch(id) {
case 1:
basicDialogEntry.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(basicDialogEntry.getWindowToken(), 0);
shippingPercent.setText(basicDialogEntry.getText().toString());
try {
if ((Float.parseFloat(basicDialogEntry.getText().toString())) < 0) {}
}catch(Exception ex) {
shippingPercent.setText("0");
}
mathCalculations();
CustomDialogPercent.this.dismiss();
}
return false;
}
});
break;
case 2:
basicDialogEntry.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(basicDialogEntry.getWindowToken(), 0);
taxPercent.setText(basicDialogEntry.getText().toString());
try {
if ((Float.parseFloat(basicDialogEntry.getText().toString())) < 0) {}
}catch(Exception ex) {
taxPercent.setText("0");
}
mathCalculations();
CustomDialogPercent.this.dismiss();
}
return false;
}
});
break;
case 3:
basicDialogEntry.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(basicDialogEntry.getWindowToken(), 0);
commissionPercent.setText(basicDialogEntry.getText().toString());
try {
if ((Float.parseFloat(basicDialogEntry.getText().toString())) < 0) {}
}catch(Exception ex) {
commissionPercent.setText("0");
}
mathCalculations();
CustomDialogPercent.this.dismiss();
}
return false;
}
});
break;
}
}
}
OK. With this code what is happening is the first time I tap each TextView they work perfectly. But once I tap any of them again the dialog boxes pop up correctly with the correct title, but values that are set back to the TextView are incorrect.
Example; i enter 8 for the shippingPercent and them 25 for the commissionPercent. And then i go back to shippingPercent and enter 5. The 5 doesn't get set. Instead it will be 25. If i keep using the dialog boxes it seems like my mathCalculations() stops working aswell.
Thanks for all the help.
Maybe you could assign a variable
activeTextView = theTextViewYouWant;
...then update activeTextView with the value you want?

Categories

Resources