Search code examples
androidbuttonandroid-activitylayoutsnackbar

simple android Snackbar not working


I was trying to show a very simple Snackbar in the MainActivity in my app, after clicking on a button. This button also leads to the start of a new activity. But after I clicked it, no Snackbar show and the new Activity started. My MainActivity is a RelativeLayout and I don't quite want to change it into CoordinatorLayout.

<RelativeLayout
 <TextView
        android:id="@+id/tvReceived"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Messages Received"
        android:textSize="25sp"
        android:gravity="center"
        android:textStyle="bold"
        android:textAllCaps="false"
        android:textColor="#3079ab"
        android:layout_marginTop="10dp"/>

    <LinearLayout
        android:id="@+id/linearMain"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvReceived"
        android:layout_marginTop="7dp"
        android:layout_marginBottom="50dp">
        <FrameLayout
            android:id="@+id/receivedList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </FrameLayout>
    </LinearLayout>

    <Button
        android:id="@+id/newMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Message"
        android:textAllCaps="false"
        android:textSize="16sp"
        android:layout_alignParentBottom="true"
        android:layout_alignEnd="@+id/linearMain"
        android:layout_marginBottom="32dp" />
</RelativeLayout>

Java code of the Snackbar:

Button btnNewSms = (Button) findViewById(R.id.newMessage);
btnNewSms.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
      Snackbar mySnackbar = Snackbar.make(v, R.string.new_message, Snackbar.LENGTH_LONG);
      mySnackbar.show();
      Intent intent = new Intent(MainActivity.this, ComposeActivity.class);
      startActivity(intent);
     }
});

What is wrong? Thanks in advance!


Solution

  • Comment your intent and run the code, the Activity is starting when the button is clicked and you are not able to see the Snackbar. You can open the Activity on the click of your button inside your Snackbar by following

     public void showMsgSnack(String msg) {
    
            snackbar = Snackbar.make(getCurrentFocus(), "Your Message here", Snackbar.LENGTH_INDEFINITE).setAction("Open", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                        //Your Intent here
                }
            });
            snackbar.show();
        }
    

    Try and let me know if it worked