Simple code below for showing the Snackbar.
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_INDEFINITE)
.setAction("Action", null).show();
}
This code correctly shows the Snackbar, when onClick
event occurs.
Also, this snackbar can be dismissed by a swipe gesture.
But by default, only Right-swipe is dismissing the Snackbar. And I am unable to dismiss it with left-swipe.
How to dismiss snackbar on left-swipe?
This will dismiss snackBar
on Left swipes (but without that animation on swipe left)
getView()
and take the snackBar
layoutsetOnTouchListener
and its Done!
public class HomeActivity extends AppCompatActivity {
private float x1,x2;
static final int MIN_DISTANCE = 150;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rel);
final Snackbar snackbar = Snackbar.make(relativeLayout, "Helloo", Snackbar.LENGTH_INDEFINITE);
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView();
layout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
break;
case MotionEvent.ACTION_UP:
x2 = event.getX();
float deltaX = x2 - x1;
if (Math.abs(deltaX) > MIN_DISTANCE)
{// Left to Right swipe action
if (x2 > x1)
{
Toast.makeText(HomeActivity.this, "Left to Right swipe ", Toast.LENGTH_SHORT).show ();
}
// Right to left swipe action
else
{
Toast.makeText(HomeActivity.this, "Right to Left swipe ", Toast.LENGTH_SHORT).show ();
snackbar.dismiss();
}
}
else
{
Toast.makeText(HomeActivity.this, "Tap or Else", Toast.LENGTH_SHORT).show ();
}
break;
}
return false;
}
});
snackbar.show();
}
}