在java Android中为自定义对话框创建一个通用类

2022-09-01 15:34:13

我的应用程序显示许多自定义对话框,例如“是/否”或“接受/取消”决定,并且在我编码时,我意识到有如此多的代码重复,遵循相同的架构。

我想构建一个通用类,但我不知道如何做到这一点,或者更确切地说,我必须以正确的方式做到这一点(接口,抽象类,继承,静态类,...

这是我目前的课程:

public class DialogTwoOptions extends Dialog {

TextView title_tv;
// Button yes_btn, no_btn;

public DialogTwoOptions(Context context) 
{
    super(context);     
    setContentView(R.layout.dialogo_sino); // a simple layout with a TextView and Two Buttons

    title_tv = (TextView) findViewById(R.id.dialogo_titulo_sino);
    // yes_btn = (Button) findViewById(R.id.dialogo_aceptar); 
    // no_btn = (Button) findViewById(R.id.dialogo_cancelar);

    View v = getWindow().getDecorView();
    v.setBackgroundResource(android.R.color.transparent);
}

 public void quitDialog(View v) {
     if (isShowing()) dismiss();
 }

 public void setTitle(String title) {
     title_tv.setText(title);
 }

}

当我需要使用这个类时,这就是我正在做的事情:

final DialogTwoOptions dialog = new DialogTwoOptions(this);

    Button yes = (Button) dialog.findViewById(R.id.dialog_yes_btn);
    Button no = (Button) dialog.findViewById(R.id.dialog_no_btn);

    yes.setOnClickListener(new Button.OnClickListener() 
    {
        public void onClick(View v)     {
            dialog.dismiss();
            // Do something 
        }
    });

    no.setOnClickListener(new Button.OnClickListener() 
    {
        public void onClick(View v)     {
            dialog.dismiss();
            // Do something
        }
    });

    dialog.show();

我相信它是可以改进的,但你怎么能这样做呢?

谢谢


答案 1

首先创建一个 Base 以保留 的实例。因此,当对话框附加到 时,您将知道创建它的实例。DialogFragmentActivityActivityActivity

public abstract class BaseDialogFragment<T> extends DialogFragment {
        private T mActivityInstance;

        public final T getActivityInstance() {
                return mActivityInstance;
        }

        @Override
        public void onAttach(Activity activity) {
                mActivityInstance = (T) activity;
            super.onAttach(activity);
        }

        @Override
        public void onDetach() {
                super.onDetach();
                mActivityInstance = null;
        }
}

然后,创建一个扩展GeneralDialogFragmentBaseDialogFragment

public class GeneralDialogFragment extends BaseDialogFragment<GeneralDialogFragment.OnDialogFragmentClickListener> {

        // interface to handle the dialog click back to the Activity
        public interface OnDialogFragmentClickListener {
            public void onOkClicked(GeneralDialogFragment dialog);
            public void onCancelClicked(GeneralDialogFragment dialog);
        }

        // Create an instance of the Dialog with the input
        public static GeneralDialogFragment newInstance(String title, String message) {
            GeneralDialogFragment frag = new GeneralDialogFragment();
            Bundle args = new Bundle();
            args.putString("title", title);
            args.putString("msg", message);
            frag.setArguments(args);
            return frag;
        }
        // Create a Dialog using default AlertDialog builder , if not inflate custom view in onCreateView
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {

            return new AlertDialog.Builder(getActivity())
                .setTitle(getArguments().getString("title"))
                .setMessage(getArguments().getString("message"))
                .setCancelable(false)
                .setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            // Positive button clicked
                            getActivityInstance().onOkClicked(GeneralDialogFragment.this);
                        }
                    }
                )
                .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            // negative button clicked
                            getActivityInstance().onCancelClicked(GeneralDialogFragment.this);
                        }
                    }
                )
                .create();
        }

    }

如果您需要使用自己的自定义布局进行对话框,请在其中膨胀布局并删除。但是添加点击侦听器,就像我解释的那样onCreateViewonCreateDialogonCreateViewonCreateDialog

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_dialog, container, false);
    return view;
}

然后,在您需要实现一个处理动作时Activityinterfacedialog

public class TryMeActivity extends 
    FragmentActivity implements GeneralDialogFragment.OnDialogFragmentClickListener {

    @Override
        public void onOkClicked(GeneralDialogFragment dialog) {
                // do your stuff
        }

        @Override
        public void onCancelClicked(GeneralDialogFragment dialog) {
                // do your stuff
        }
}

最后,在需要时显示您的DialogActivity

    GeneralDialogFragment generalDialogFragment =
        GeneralDialogFragment.newInstance("title", "message");
    generalDialogFragment.show(getSupportFragmentManager(),"dialog");

希望这有帮助。我相信这种方法是优化的方法之一,但也可能有不同的方法 。


答案 2

我遇到了像你这样的问题。而且所有在堆栈溢出中都不符合我想要的。所以我创建了自己的对话框类,它可以像AlertDialog.Builder类一样使用。

在我的对话xml中.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@drawable/drconner">

    <LinearLayout
        android:id="@+id/under"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <TextView
        android:id="@+id/malertTitle"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:padding="5dp"
        android:textSize="25sp"
        android:textColor="#ffffff"
        android:drawablePadding="2dp"
        android:background="@color/colorPrimaryDark"
        />

    <TextView
        android:id="@+id/aleartMessage"
        android:layout_width="match_parent"
        android:layout_height="75dp"
        android:padding="5dp"
        android:textSize="18sp"
        android:textColor="@color/colorAccent"/>
    </LinearLayout>

    <LinearLayout
        android:layout_below="@+id/under"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="1dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/aleartYes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <Button
            android:id="@+id/aleartNo"
            android:layout_marginLeft="30dp"
            android:layout_marginStart="30dp"
            android:layout_marginRight="3dp"
            android:layout_marginEnd="3dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />


    </LinearLayout>


</RelativeLayout>

对于对话框形状,我只创建简单的形状xml - drconner.xml

<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">

    <corners android:radius="5dp"/>
    <stroke android:color="@color/colorPrimaryDark" android:width="2dp"/>


</shape>

对于自定义警报,我创建了Alear.java如下所示

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;



/**
 * Created by sanyatihan on 27-Dec-16.
 */

public class Alert extends Dialog {

    private String message;
    private String title;
    private String btYesText;
    private String btNoText;
    private int icon=0;
    private View.OnClickListener btYesListener=null;
    private View.OnClickListener btNoListener=null;

    public Alert(Context context) {
        super(context);
    }

    public Alert(Context context, int themeResId) {
        super(context, themeResId);
    }

    protected Alert(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.dialogxml);
        TextView tv = (TextView) findViewById(R.id.malertTitle);
        tv.setCompoundDrawablesWithIntrinsicBounds(icon,0,0,0);
        tv.setText(getTitle());
        TextView tvmessage = (TextView) findViewById(R.id.aleartMessage);
        tvmessage.setText(getMessage());
        Button btYes = (Button) findViewById(R.id.aleartYes);
        Button btNo = (Button) findViewById(R.id.aleartNo);
        btYes.setText(btYesText);
        btNo.setText(btNoText);
        btYes.setOnClickListener(btYesListener);
        btNo.setOnClickListener(btNoListener);

    }



       public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setIcon(int icon) {
        this.icon = icon;
    }

    public int getIcon() {
        return icon;
    }

    public void setPositveButton(String yes, View.OnClickListener onClickListener) {
        dismiss();
        this.btYesText = yes;
        this.btYesListener = onClickListener;


    }

    public void setNegativeButton(String no, View.OnClickListener onClickListener) {
        dismiss();
        this.btNoText = no;
        this.btNoListener = onClickListener;


    }
}

要使用此 Alert 类,只需使用 AlertDialog.Builder 类即可

例如:

final Alert mAlert = new Alert(this);
        mAlert.setTitle("This is Error Warning");
        mAlert.setIcon(android.R.drawable.ic_dialog_alert);
        mAlert.setMessage("Do you want to delete?");
        mAlert.setPositveButton("Yes", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAlert.dismiss();
                //Do want you want
            }
        });

        mAlert.setNegativeButton("No", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAlert.dismiss();
                //Do want you want
            }
        });

        mAlert.show();

最主要的是你应该在onClick中调用dissume()函数。我希望这对你有所帮助。并让我知道这是否是你想要的。您可以在 dialogxml 中根据需要更改布局.xml。


推荐