How to set Context menu to onBackPressedButton? - java

I'm trying to set Context menu to onBackPressedButton like "Are you sure to quit?"
Here I override onBackPressed:
I don't know how to call menu. What should I register here?
#Override
public void onBackPressed() {
registerForContextMenu();
return;
}
or what view should I attach?
#Override
public void onBackPressed() {
this.openContextMenu();
return;
}
Should I create viewList to it?
I've overridden onCreateContextMenu:
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
menu.add(0,YES,0,"Yes");
menu.add(0,NO,0,"No");
}
I've also overridden and onContextItemSelected:
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case YES:
finish();
break;
case NO:
break;
}
return super.onContextItemSelected(item);
}
How must I do it?

Just call onBackPressed() method in your class. Find a sample code below.
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
LoginActivity.super.onBackPressed();
finish();
}
}).create().show();
}

Related

Android Studio menu opens all items on every item pick

I am currently working on an Android Studio project, and I've stumbled into an issue, no matter which option I pick in the menu, it changes activity to all of them in a row, and then crashes.
Here's my home page menu functions:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
menu.removeItem(R.id.HomePage);
if (sp.getLong("User_Id", -1) != -1) {
menu.removeItem(R.id.Login);
menu.removeItem(R.id.SignUp);
}
else {
menu.removeItem(R.id.LogOut);
}
if (sp.contains("User_Id")){
if (!database.userDao().GetUserById(sp.getLong("User_Id", -1)).getUserEmail().equals(R.string.admin_email))
menu.removeItem(R.id.UserList);
}
else
menu.removeItem(R.id.UserList);
return true;
}
#SuppressLint("NonConstantResourceId")
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.SignUp: {
startActivity(new Intent(MainActivity.this, RegisterActivity.class));
}
case R.id.Login: {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
case R.id.UserList: {
startActivity(new Intent(MainActivity.this, UserActivity.class));
}
case R.id.LogOut:{
builder.setMessage(R.string.logout_dialog_message).setTitle(R.string.logout_dialog_title).setCancelable(true).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
editor.clear();
editor.commit();
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
overridePendingTransition(0, 0);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
case R.id.About: {
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_about_dialog);
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
dialog.getWindow().getAttributes().windowAnimations = R.style.animation;
ImageView image = dialog.findViewById(R.id.IVLogo);
TextView text = dialog.findViewById(R.id.TVText);
image.setBackground(getDrawable(R.drawable.logo));
text.setText("About us: We are regel2, the new best second hand app. In this app, you are able to buy and sell any product that you want, for any price that you want, all inside 1 app.");
dialog.show();
}
}
return super.onOptionsItemSelected(item);
}
Note: It opens even deleted menu items (Aka menu.removeItem(___)) and it doesn't happen when I click on the about item, which may act differently because it's a dialog.
You need to put
break;
as the last statement of every case block, otherwise execution will continue to the end.

Creating a reusable class

I have an application running in Android, i wanna create a Menu and repeat in some activities, that menu calls Intent for open others activities.
How can i do this?
Think maybe i can create a class, but i getting errors. Where can i create a class for that? Inside onCreate method or not?
And how can i reuse the menu in another activity?
Thanks!!
Here is my menu code:
menu_button = (Button) findViewById(R.id.menu_button);
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this, menu_button);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
Intent vista = new Intent(MainActivity.this, openCamera.class);
MainActivity.this.startActivity(vista);
}
return true;
/*
Toast.makeText(MainActivity.this, "" + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
*/
}
});
popupMenu.show();
}
});
If the menu is always the same and you want to reuse it in more than one activity, you just define it like this:
public class TestMenu {
private final PopupMenu popupMenu;
public TestMenu(final Activity activity, View anchor) {
popupMenu = new PopupMenu(activity, anchor);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
Intent vista = new Intent(activity, openCamera.class);
activity.startActivity(vista);
}
return true;
}
});
}
public void show() {
popupMenu.show();
}
}
And then use it in your activity like this:
public class TestActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button menu_button = (Button) findViewById(R.id.menu_button);
TestMenu myMenu = new TestMenu(this, menu_button);
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myMenu.show();
}
});
}
}

How to prevent back button until confirmation message?

In Android Studio, I've used a WebView. So if a user clicks the back button, I want to show a confirmation message before app close.
This is my current code which I used, but it is not working every time
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
The above code is working fine.
If you want to navigate the WebView back to the previous page use below one.
#Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
}else{
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
super.onBackPressed();
}
})
.setNegativeButton("No", null)
.show();
}
}
Can you try with it. Hope it works
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
// If web view have back history, then go to the web view back history
webView.goBack();
} else {
// Ask the user to exit the app or stay in here
exitApp();
}
}
public void exitApp() {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Please confirm");
builder.setMessage("Do you want to exit the app?");
builder.setCancelable(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
// Create the alert dialog using alert dialog builder
AlertDialog dialog = builder.create();
// Finally, display the dialog when user press back button
dialog.show();
}
You have to call your confirmation message method inside your Activities onBackPressed Method
#Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
onBackPressed() // This is Your Confirmation Dialog method
}
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
}else {
new AlertDialog.Builder(this)
.setTitle("Are you sure?")
.setMessage("Do you want to exit?")
.setPositiveButton("Close", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
This worked for me. Hope it works.

Hide AlertDialog in specific activity

I have one Quote application. When I open the application's MainActivity, if there is new data updated on the server side, one AlertDialog is shown for going to SettingsActivity. It takes some time for appear so if the app is already on SettingsActivity, it is still showing the AlertDialog to go to SettingsActivity.
I want to prevent the AlertDialog from showing in SettingsActivity but continue showing in other activities. My code for AlertDialog is below. How can I do that?
public class UpdatesDialogActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(UpdatesDialogActivity.this);
builder.setTitle("Download New Status");
builder.setMessage("There Are New Status Arrived. Push Download Button From Settings.");
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(UpdatesDialogActivity.this, SettingsActivity.class);
finish();
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
finish();
return false;
}
});
builder.show();
}
// ==============================================================================
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
You can go for an 'instanceof' check and see if the current activity is settings or else.
if(activity instanceof SettingsActivity){
//don;t show dialog
}else{
//show dialog
}
Hope this will help.

How to create a alert dialog box when back button is pressed?

I want to show a alert dialog box to the user when the back button is pressed..For example :Are you sure want to exit ?.I am not having a problem in creating a alert dialog box..I am having a problem in where to call this dialog box method().
This is my HomeScreen.java
public class HomeScreen extends TabActivity {
ConferenceOpenHelper helper_ob;
Cursor cursorHome;
ProfileEditScreen profileEditScreen;
ConferenceAdapter adapter;
EcMeeting meeting;
final Context context = this;
public static int HOMETEMP = 1;// Constant for Deleting the last created id
// in edit profile screen (Cancel)
public static String HOME = "home";// constant for updating status column
public static String CUSTOM_DIALER = "custom";
public static String TEMPLATE = "template";// constant for updating status // column
public static TabHost tabHost;
public static final int QUICK_START = 1;// Constant for menu options
public static final int TEMPLATE_SCREEN = 2;// Constant for menu options
public static final int USER_GUIDE = 3;// Constant for menu options
public static final int QUICK_CALL = 4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab);
Resources ressources = getResources();
tabHost = getTabHost();
// Android tab
Intent photo = new Intent().setClass(this,EcMeeting.class);
TabSpec tabSpecphoto = tabHost
.newTabSpec("Calendar")
.setIndicator("Calendar", ressources.getDrawable(R.drawable.calendartab))
.setContent(photo);
// Apple tab
Intent intentApple = new Intent().setClass(this,CallListScreen.class);
TabSpec tabSpecApple = tabHost
.newTabSpec("Calls")
.setIndicator("Calls", ressources.getDrawable(R.drawable.ic_action_device_access_call))
.setContent(intentApple);
// Windows tab
Intent intentWindows = new Intent().setClass(this,UserSettingActivity.class);
TabSpec tabSpecWindows = tabHost
.newTabSpec("Settings")
.setIndicator("Settings", ressources.getDrawable(R.drawable.ic_action_setting))
.setContent(intentWindows);
// add all tabs
tabHost.addTab(tabSpecphoto);
tabHost.addTab(tabSpecApple);
tabHost.addTab(tabSpecWindows);
//set Windows tab as default (zero based)
/*tabHost.setCurrentTab(0);*/
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#d3d3d3"));
}
tabHost.getTabWidget().setCurrentTab(0);
/*tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#C35817"));*/
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, QUICK_START, 0, "Quick Start").setIcon(R.drawable.ic_menu_add_icon);
menu.add(0, USER_GUIDE, 0, "User Guide").setIcon(R.drawable.ic_menu_guide_icon);
return true;
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case QUICK_START:
startActivity(new Intent(this, ConfDialerScreen.class));
break;
case USER_GUIDE:
startActivity(new Intent(this, UserGuideScreen.class));
break;
}
return true;
}
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#8A4117"));
}
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#C35817"));
}
}
This is the method() to create alert dialog
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
Now ,I really did not know where to call this method.Could someone give any Idea?
when user press the back button I want to show the alert Dialog.
Try below code:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialogOnBackPress();
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void dialogOnBackPress() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
Use this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Alert Message:");
builder.setMessage("Do you want to save this image to your file??");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
// do your stuff
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
you can this code modify acc. to req.
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
#Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
dialog.dismiss();
}
return true;
}
});
do not call super.onBackPressed(); in onBackPressed
Else you can simply add onBackPressed() in activity_main.xml(tab.xml) as
android:onClick="onBackPressed"
mention it in your button properties

Categories