使用Snackbar之前,须导入com.android.support:design
使用示例
package com.bu_ish.snackbar_test; import android.graphics.Color;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast; public class SnackbarExampleActivity extends AppCompatActivity {
private static final String TAG = SnackbarExampleActivity.class.getName(); @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snackbar_example);
findViewById(R.id.indefiniteButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar snackbar = Snackbar.make(v, "无限时长的Snackbar", Snackbar.LENGTH_INDEFINITE);
snackbar.getView().setBackgroundColor(getResources().getColor(R.color.colorAccent));
snackbar.setActionTextColor(Color.WHITE);
snackbar.setAction("关闭", new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "已关闭", Toast.LENGTH_SHORT).show();
}
});
snackbar.addCallback(new Snackbar.Callback() {
@Override
public void onShown(Snackbar sb) {
super.onShown(sb);
Log.d(TAG, "Snackbar.Callback.onShown(Snackbar) called");
} @Override
public void onDismissed(Snackbar transientBottomBar, int event) {
super.onDismissed(transientBottomBar, event);
Log.d(TAG, "Snackbar.Callback.onDismissed(Snackbar, int) called");
}
});
snackbar.show();
}
});
findViewById(R.id.longButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar snackbar = Snackbar.make(v, "长时效的Snackbar", Snackbar.LENGTH_LONG);
snackbar.show();
}
});
findViewById(R.id.shortButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar snackbar = Snackbar.make(v, "短时效的Snackbar", Snackbar.LENGTH_SHORT);
snackbar.getView().setBackgroundColor(getResources().getColor(R.color.colorPrimary));
snackbar.show();
}
});
}
}
效果图