Trong bài viết này, chúng tôi nói về Snackbar trong Android.
Step 1: Thiết kế layout màn hình chính
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_show_snackbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Snackbar"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 2: Code trong file MainActivity.java
package com.tnv.thongcodelab_snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.material.snackbar.Snackbar;
public class MainActivity extends AppCompatActivity {
private Button btnShowSnackbar;
// this is view container controls, snackbar will be show at bottom of this container
private ConstraintLayout mainContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainContent = findViewById(R.id.main_content);
btnShowSnackbar = findViewById(R.id.btn_show_snackbar);
btnShowSnackbar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showSnackBar(mainContent);
}
});
}
private void showSnackBar(ConstraintLayout mainContent){
Snackbar snackbar = Snackbar.make(mainContent, "Không có mạng", Snackbar.LENGTH_LONG);
snackbar.setAction("Thử lại", new View.OnClickListener() {
@Override
public void onClick(View view) {
// dismiss
snackbar.dismiss();
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
sbView.setBackgroundColor(Color.YELLOW);
TextView textView = sbView.findViewById(R.id.snackbar_text);
textView.setTextColor(Color.BLUE);
snackbar.show();
}
}
Tags
Android