purplewind
purplewind

Reputation: 351

How to set Onclicklistener for actions in snackbar android?

I am trying to set actions in a snackbar. I have the following code:

Snackbar.make(cb,lvMain.getChildCount()+" hotspots selected.",Snackbar.LENGTH_INDEFINITE).setAction("COPY TO",mOnClickListener).setActionTextColor(Color.RED).show();

How do I declare the listener "mOnClickListener" for the action ?

Upvotes: 3

Views: 6718

Answers (3)

cutiko
cutiko

Reputation: 10517

I see the Kotlin way to do so is missing so I want to add my 2 cents:

Snackbar.make(view, "", Snackbar.LENGTH_INDEFINITE).apply {
    setAction(R.string.dismiss) { this.dismiss() }
    show()
}

The nice thing is the apply make the extra variable for dismissing the snackbar not needed

The apply also returns whatever its pass so you can apply{...}.show()

Upvotes: 0

Shree Krishna
Shree Krishna

Reputation: 8562

Declare View.OnClickListener mOnClickListener; as class variable in Activity like,

public class MainActivity extends AppCompatActivity {
    View.OnClickListener mOnClickListener;
   // extra codes
}

then you can simply do like this,

   mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Handle onclick here
        }
    };

See here for full example.

Upvotes: 0

Muhammad Younas
Muhammad Younas

Reputation: 1603

Snackbar snackbar = Snackbar
        .make(cb,lvMain.getChildCount()+" hotspots selected.",Snackbar.LENGTH_INDEFINITE)
        .setAction("COPY TO", new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

snackbar.show();

Upvotes: 9

Related Questions