It may be easier for those who are familiar with android code. I'am newbie here... I just working on to do an action after my snackbar dismissed. I read tutorial here but still not give me clear direction.
adapterTutorSubject.setOnClickListener(new AdapterTutorSubject.OnClickListener() {
#Override
public void onItemClick(View view, TutorSubject obj, int pos) {
Snackbar.make(parent_view, "Item " + obj.subjectName + " clicked", Snackbar.LENGTH_SHORT).show();
//On snackbar dismissed, then go to this page
Intent intent = new Intent(getApplicationContext(), ChapterListActivity.class);
startActivity(intent);
}
});
Thanks!
You could simply setCallback as shown here.
Modify the code like:
adapterTutorSubject.setOnClickListener(new AdapterTutorSubject.OnClickListener() {
#Override
public void onItemClick(View view, TutorSubject obj, int pos) {
Snackbar snack = Snackbar.make(parent_view, "Item " + obj.subjectName + " clicked", Snackbar.LENGTH_SHORT);
snack.setCallback(new Snackbar.Callback() {
#Override
public void onDismissed(Snackbar snackbar, int event) {
if (event == Snackbar.Callback.DISMISS_EVENT_TIMEOUT) {
// Snackbar closed on its own
}
}
#Override
public void onShown(Snackbar snackbar) {
//Do something in shown
}
});
snack.show();
}
});
Hope it helps!!!
Related
I wanted to make a snackbar dialog on double press to exit...(java)
Requested with these
On 1st time back pressed show dialogue " press back again to exit " for 2 seconds
On pressing back again show "do you want to exit ? " with the
confirmation button for 2 seconds
As like below -
Create id for your layout in activity_main
CoordinatorLayout coordinatorLayout;
#Override
public void onBackPressed() {
coordinatorLayout= (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
if (!doubleBackToExitPressedOnce) {
this.doubleBackToExitPressedOnce = true;
Snackbar.make(coordinatorLayout, "Do you really want to exit?", Snackbar.LENGTH_LONG)
.setAction("YES", new View.OnClickListener() {
#Override
public void onClick(View view) {
//button action here
System.exit(0);
}
}).setActionTextColor(Color.YELLOW)
.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
Hope this helps
Here is the solution for you -
private final long DOUBLE_PRESS_BACK_TO_EXIT_TIME = 2000;
boolean doubleBackPressed = false;
#Override
public void onBackPressed() {
// todo: show the snackbar here.
this.doubleBackPressed = true;
utils.showToastLong(getString(R.string.press_again_to_exit));
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackPressed = false;
// todo: hide the snackbar here.
}
}, DOUBLE_PRESS_BACK_TO_EXIT_TIME);
}
To customize the Snackbar you may follow this link
I want to get informed when Snackbar is closed. In an activity I use Snackbar and then I call another activity and I want to show Snackbar and when it has been already closed want to startActivity(NextActivity). How could I manage it?
Snackbar.make(view, "Some text", Snackbar.LENGTH_SHORT)
.setCallback(new Snackbar.Callback() {
#Override
public void onDismissed(Snackbar snackbar, int event) {
super.onDismissed(snackbar, event);
startActivity(this, NextActivity.class);
}
}).show();
Define an action
.setAction("Go To Next Activity", mOnClickListener);
define onClickListenet as follows:
mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
snackBar.dismiss(); // to close the snackbar
// startActivity(nextActivityIntent)
}
};
More Info Here
I'm late but I hope it works for you
Scaffold.of(thisContext).showSnackBar(snackBar).closed.then((value){
print('snackbar closed');
});
If i call the snackbar multiple times in a row, only the last snackbar item is displayed.
e.g. with the codes below, only Item 3 would be shown. it seems that Snackbar.LENGTH_LONG is ignored (and set to zero?) for item 1 and 2.
Snackbar.make(view, "Item 1", Snackbar.LENGTH_LONG).show();
Snackbar.make(view, "Item 2", Snackbar.LENGTH_LONG).show();
Snackbar.make(view, "Item 3", Snackbar.LENGTH_LONG).show();
yet in the google documents, I see that it is possible to queue the messages.
public boolean isShownOrQueued ()
Returns whether this Snackbar is currently being shown,
or is queued to be shown next.
so how do we actually queue the snackbar?
Here is a partial snippet that solves your problem, although it might not
be the correct way to go about things:
//using a queue to pass string to the snackbar
Queue<String> myQueue = new LinkedList<String>();
myQueue.offer("item 1");
myQueue.offer("item 2");
myQueue.offer("item 3");
displaysnack(myQueue, view);
public void displaysnack(final Queue dQueue, final View view){
Snackbar.make(view, (String)dQueue.poll(), Snackbar.LENGTH_LONG).setCallback(new Snackbar.Callback() {
#Override
public void onDismissed(Snackbar snackbar, int event) {
switch (event) {
case Snackbar.Callback.DISMISS_EVENT_ACTION:
Toast.makeText(getApplicationContext(), "Clicked the action", Toast.LENGTH_LONG).show();
break;
//once the timeout expires, display the next one in the queue.
case Snackbar.Callback.DISMISS_EVENT_TIMEOUT:
Toast.makeText(getApplicationContext(), "Showing: "+ (dQueue.size()), Toast.LENGTH_SHORT).show();
if (dQueue.size()>0){displaysnack(dQueue, view);}
break;
case Snackbar.Callback.DISMISS_EVENT_CONSECUTIVE:
//Toast.makeText(getApplicationContext(), "Multiple Shown", Toast.LENGTH_SHORT).show();
break;
}
}
I also needed to implement a queue of snackbars but did not find ready solution. So I decided to implement it on my own. You can try it https://github.com/AntonyGolovin/FluentSnackbar.
Just call important() on Builder and it will be added to the queue.
I also implemented my own, probably not the slickest but suited my needs. Its in C# for Xamarin though.
public class SnackbarManager : Snackbar.Callback
{
List<Snackbar> snackbarsWaiting;
List<Snackbar> snackbarsHolding;
public SnackbarManager()
{
snackbarsWaiting = new List<Snackbar>();
snackbarsHolding = new List<Snackbar>();
}
public void AddToQueue(Snackbar snackbar)
{
if (snackbar.Duration == Snackbar.LengthIndefinite) snackbar.SetDuration(Snackbar.LengthLong);
snackbar.SetCallback(this);
if (snackbarsWaiting.Count > 0 && snackbarsWaiting[0].IsShown) snackbarsHolding.Add(snackbar);
else snackbarsWaiting.Add(snackbar);
}
public void Show()
{
if (snackbarsWaiting.Count > 0 && !snackbarsWaiting[0].IsShown)
snackbarsWaiting[0].Show();
}
public override void OnDismissed(Snackbar snackbar, int evt)
{
base.OnDismissed(snackbar, evt);
snackbarsWaiting.Remove(snackbar);
if (snackbarsHolding.Count > 0)
{
snackbarsWaiting.AddRange(snackbarsHolding);
snackbarsHolding.Clear();
}
if (snackbarsWaiting.Count > 0) snackbarsWaiting[0].Show();
}
}
I met this problem too, this is my solution.
static List<Snackbar> snackBarList = new ArrayList<>();
public static void mySnackBar(CoordinatorLayout coordinatorLayout, String s,boolean queued) {
Snackbar snackbar = Snackbar.make(coordinatorLayout, s, Snackbar.LENGTH_SHORT);
if (queued) {
//if true set onDismiss CallBack
snackbar.setCallback(new Snackbar.Callback()
{
#Override
public void onDismissed(Snackbar currentSnackbar, int event) {
super.onDismissed(currentSnackbar, event);
//first remove current snackBar in List, then if List not empty show the first one
snackBarList.remove(currentSnackbar);
if (snackBarList.size() > 0)
snackBarList.get(0).show();
}
});
//add (set callback) snackBar to List
snackBarList.add(snackbar);
//the beginning
if (snackBarList.size() == 1)
snackBarList.get(0).show();
} else snackbar.show();
}
I've written a library that do just that. It also includes progressBar. Try it out https://github.com/tingyik90/snackprogressbar
i am using Swipe menu list View from the Githu
https://github.com/baoyongzhang/SwipeMenuListView
According to my project requirement i need to stop some list View to Swipe
for example i want to stop the list item on the postion 5
how i would do that
mListView.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {
#Override
public void onSwipeStart(int position) {
if (positon == 5) {
Toast.makeText(getApplicationContext(), "you are not Allow to Swipe", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onSwipeEnd(int position) {
}
});
You can create a private instance of the listener and than set it to the mListView if a condition is met and if you want to not allow the swiping to be active you can simply set the onSwipeListener to null like this:
private SwipeMenuListView.OnSwipeListener swipeListener = new SwipeMenuListView.OnSwipeListener() {
#Override
public void onSwipeStart(int i) {
}
#Override
public void onSwipeEnd(int i) {
}
});
if (condtion) {
Toast.makeText(getApplicationContext(), "you are not Allow to Swipe", Toast.LENGTH_SHORT).show();
//disable swiping
mListView.setOnSwipeListener(null);
}else{
//allow swiping
mListView.setOnSwipeListener(swipeListener);
}
you can use BaseSwipListAdapter and change condition according your requirments.
#Override
public boolean getSwipEnableByPosition(int position) {
if(position==5){
return false;
}
return true;
}
I wrote a piece of code that will give the user a prompt asking them to press back again if they would like to exit. I currently have my code working to an extent but I know it is written poorly and I assume there is a better way to do it. Any suggestions would be helpful!
Code:
public void onBackPressed(){
backpress = (backpress + 1);
Toast.makeText(getApplicationContext(), " Press Back again to Exit ", Toast.LENGTH_SHORT).show();
if (backpress>1) {
this.finish();
}
}
I would implement a dialog asking the user if they wanted to exit and then call super.onBackPressed() if they did.
#Override
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 OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
WelcomeActivity.super.onBackPressed();
}
}).create().show();
}
In the above example, you'll need to replace WelcomeActivity with the name of your activity.
You don't need a counter for back presses.
Just store a reference to the toast that is shown:
private Toast backtoast;
Then,
public void onBackPressed() {
if(USER_IS_GOING_TO_EXIT) {
if(backtoast!=null&&backtoast.getView().getWindowToken()!=null) {
finish();
} else {
backtoast = Toast.makeText(this, "Press back to exit", Toast.LENGTH_SHORT);
backtoast.show();
}
} else {
//other stuff...
super.onBackPressed();
}
}
This will call finish() if you press back while the toast is still visible, and only if the back press would result in exiting the application.
I use this much simpler approach...
public class XYZ extends Activity {
private long backPressedTime = 0; // used by onBackPressed()
#Override
public void onBackPressed() { // to prevent irritating accidental logouts
long t = System.currentTimeMillis();
if (t - backPressedTime > 2000) { // 2 secs
backPressedTime = t;
Toast.makeText(this, "Press back again to logout",
Toast.LENGTH_SHORT).show();
} else { // this guy is serious
// clean up
super.onBackPressed(); // bye
}
}
}
Both your way and #Steve's way are acceptable ways to prevent accidental exits.
If choosing to continue with your implementation, you will need to make sure to have backpress initialized to 0, and probably implement a Timer of some sort to reset it back to 0 on keypress, after a cooldown period. (~5 seconds seems right)
You may also need to reset counter in onPause to prevent cases when user presses home or navigates away by some other means after first back press. Otherwise, I don't see an issue.
If you want to exit your application from direct Second Activity without going to First Activity then try this code..`
In Second Activity put this code..
#Override
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) {
setResult(RESULT_OK, new Intent().putExtra("EXIT", true));
finish();
}
}).create().show();
}
And Your First Activity Put this code.....
public class FirstActivity extends AppCompatActivity {
Button next;
private final static int EXIT_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
next = (Button) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(FirstActivity.this, SecondActivity.class), EXIT_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EXIT_CODE) {
if (resultCode == RESULT_OK) {
if (data.getBooleanExtra("EXIT", true)) {
finish();
}
}
}
}
}
This is the best way, because if user not back more than two seconds then reset backpressed value.
declare one global variable.
private boolean backPressToExit = false;
Override onBackPressed Method.
#Override
public void onBackPressed() {
if (backPressToExit) {
super.onBackPressed();
return;
}
this.backPressToExit = true;
Snackbar.make(findViewById(R.id.yourview), getString(R.string.exit_msg), Snackbar.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
backPressToExit = false;
}
}, 2000);
}
additionally, you need to dissmis dialog before calling activity.super.onBackPressed(), otherwise you'll get "Activity has leaked.." error.
Example in my case with sweetalerdialog library:
#Override
public void onBackPressed() {
//super.onBackPressed();
SweetAlertDialog progressDialog = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
progressDialog.setCancelable(false);
progressDialog.setTitleText("Are you sure you want to exit?");
progressDialog.setCancelText("No");
progressDialog.setConfirmText("Yes");
progressDialog.setCanceledOnTouchOutside(true);
progressDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.dismiss();
MainActivity.super.onBackPressed();
}
});
progressDialog.show();
}
use to .onBackPressed() to back Activity specify
#Override
public void onBackPressed(){
backpress = (backpress + 1);
Toast.makeText(getApplicationContext(), " Press Back again to Exit ", Toast.LENGTH_SHORT).show();
if (backpress>1) {
this.finish();
}
}
I just had this issue and solved it by adding the following method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// click on 'up' button in the action bar, handle it here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
You can also use onBackPressed by following ways using customized Toast:
enter image description here
customized_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/txtMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="#drawable/ic_white_exit_small"
android:drawableLeft="#drawable/ic_white_exit_small"
android:drawablePadding="8dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:gravity="center"
android:textColor="#android:color/white"
android:textSize="16sp"
android:text="Press BACK again to exit.."
android:background="#drawable/curve_edittext"/>
MainActivity.java
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
android.os.Process.killProcess(Process.myPid());
System.exit(1);
return;
}
this.doubleBackToExitPressedOnce = true;
Toast toast = new Toast(Dashboard.this);
View view = getLayoutInflater().inflate(R.layout.toast_view,null);
toast.setView(view);
toast.setDuration(Toast.LENGTH_SHORT);
int margin = getResources().getDimensionPixelSize(R.dimen.toast_vertical_margin);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, margin);
toast.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
Use this, it may help.
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Message")
.setMessage("Do you want to exit app?")
.setNegativeButton("NO", null)
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
UserLogin.super.onBackPressed();
}
}).create().show();
}
implementing onBackPressed() by System time, if pressed twice within 2 sec, then will exit
public class MainActivity extends AppCompatActivity {
private long backPressedTime; // for back button timing less than 2 sec
private Toast backToast; // to hold message of exit
#Override
public void onBackPressed() {
if (backPressedTime + 2000 > System.currentTimeMillis()) {
backToast.cancel(); // abruptly cancles the toast when pressed BACK Button *back2back*
super.onBackPressed();
} else {
backToast = Toast.makeText(getBaseContext(), "Press back again to exit",
Toast.LENGTH_SHORT);
backToast.show();
}
backPressedTime = System.currentTimeMillis();
}
}