AlertDialogFragment
1. 수요 UI 다이어그램
대략적인 렌더링은 아래 그림과 같이 간단한 알림 팝업 창으로 TextView와 취소 또는 확인을위한 두 개의 클릭 가능한 Button 버튼이 있습니다.
둘째, 코드 설계 단계
팝업 창의 디자인 및 사용은 5 단계로 나뉩니다.
(1) 드로어 블 :
dialog_background.xml 디자인, (2)에서 사용 된 배경 :
모양
모서리 : 반경
솔리드 : 색상
및 기타 속성 설정.
(2) layout.xml :
dialog_background.xml을 배경으로 사용하는 alert_dialog.xml 디자인 .
(3) AlertDialogFragment.java , 팝업 창 디자인
(4) 해당 showAlertDialog 메서드를 정의하는 도구 클래스 DialogUtils 를 정의합니다.
(5) 메인 인터페이스 MainActivity의 해당 클릭 이벤트에서 showAlertDialog 메서드를 호출하여 팝업 창을 표시합니다.
셋, 소스 코드
처음 4 단계의 코드는 향후 직접 재사용 할 수 있으며, 5 단계는 실제 개발 요구에 따라 약간 수정할 수 있습니다.
(1) 드로어 블 :
dialog_background.xml , 전체 배경 :
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="15dp" />
<solid android:color="@color/cardview_shadow_start_color" />
</shape>
색상 값, 모양 등은 모두 여기에서 정의 할 수 있습니다.
둥근 모서리 15dp, 색상 값, 불투명도 등
(2) layout.xml :
alert_dialog.xml 디자인
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/dialog_background">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="确认要关闭超速报警吗?"
android:textColor="@color/white"
android:textSize="22sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="50dp"
android:text="取消"
android:background="@color/design_default_color_error"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/title" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
<Button
android:id="@+id/sure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="确认"
android:background="@color/design_default_color_error"
app:layout_constraintBottom_toBottomOf="@+id/cancel"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline2"
app:layout_constraintTop_toTopOf="@+id/cancel" />
</androidx.constraintlayout.widget.ConstraintLayout>
(1) : dialog_background.xml의 드로어 블을 배경으로 사용하여 팝업창의 인터페이스를 설계합니다.
(3)
AlertDialogFragment.java : DialogFragment를 상속합니다.
(2)에 정의 된 xml에 따라 대화 상자를 그리고 컨트롤에 클릭 이벤트를 추가합니다.
public class AlertDialogFragment extends DialogFragment {
private AlertDialogFragmentListener listener;
private String title;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
Bundle arguments = getArguments();
title = arguments.getString("title");
View view = inflater.inflate(R.layout.alert_dialog, container, false);
TextView titleText = view.findViewById(R.id.title);
Button cancel = view.findViewById(R.id.cancel);
Button sure = view.findViewById(R.id.sure);
titleText.setText(title);
cancel.setOnClickListener(v -> getDialog().cancel());
sure.setOnClickListener(v -> {
if (listener != null) {
listener.onSure();
}
getDialog().cancel();
});
return view;
}
@Override
public void onStart() {
super.onStart();
Dialog dialog = getDialog();
if (dialog != null ) {
DisplayMetrics dm = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
int height = (int) (dm.heightPixels * 0.65);
dialog.getWindow().setLayout((int) (dm.widthPixels * 0.5), height);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
}
public interface AlertDialogFragmentListener {
void onSure();
}
public void setListener(AlertDialogFragmentListener listener) {
this.listener = listener;
}
}
onCreateView 및 onStart와 같은 메소드에 익숙합니다.
OK 버튼을 클릭하면 onSure () 메서드가 포함 된 인터페이스가 외부에 노출됩니다.
(4) 해당 showAlertDialog 메서드를 정의하는 도구 클래스 DialogUtils .
같은 종류의 팝업창의 클릭 이벤트를 재사용하는 것이 편리합니다.
public class DialogUtils {
public static void showAlertDialog(
AppCompatActivity activity,
String title,
AlertDialogFragment.AlertDialogFragmentListener listener) {
AlertDialogFragment fragment = new AlertDialogFragment();
Bundle bundle = new Bundle();
bundle.putString("title", title);
fragment.setArguments(bundle);
fragment.setListener(listener);
fragment.show(activity.getSupportFragmentManager(), "fragment");
}
}
(5) MainActivity와 같은 메인 인터페이스의 해당 클릭 이벤트에서 상황에 따라 showAlertDialog 메서드를 호출하여 팝업 창을 표시합니다.
다음과 같이 :
onClick의 코드는 다음과 같습니다.
@Override
public void onClick(View v) {
if (isQuickOverSpeedAlarmOpen) {
DialogUtils.showAlertDialog(this,
String.format(getString(R.string.confirm_close_dialog),
getString(R.string.over_speed_alarm)),
() -> {
changeIsOpen(view);
ToastUtils.show(String.format(getString(R.string.has_closed),
getString(R.string.over_speed_alarm)));
});
break;
}
}
문자열에서 참고 : %에서 % 사용을 해제 하시겠습니까?