Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/195.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java Android中为自定义对话框创建通用类_Java_Android_Generics_Dialog - Fatal编程技术网

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

在java Android中为自定义对话框创建通用类,java,android,generics,dialog,Java,Android,Generics,Dialog,我的应用程序显示了许多自定义对话框,如Yes/No或Accept/Cancel Decisions,当我编写代码时,我意识到有太多代码重复,遵循相同的模式 我想构建一个通用类,但我不知道如何实现它,或者更确切地说,不知道如何正确实现它(接口、抽象类、继承、静态类等等) 这是我目前的课程: public class DialogTwoOptions extends Dialog { TextView title_tv; // Button yes_btn, no_btn; public Dia

我的应用程序显示了许多自定义对话框,如Yes/No或Accept/Cancel Decisions,当我编写代码时,我意识到有太多代码重复,遵循相同的模式

我想构建一个通用类,但我不知道如何实现它,或者更确切地说,不知道如何正确实现它(接口、抽象类、继承、静态类等等)

这是我目前的课程:

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();
我相信这是可以改进的,但是你怎么能做到呢

谢谢

您可以使用和


首先创建一个基本的
对话框片段
,以保留
活动的实例
。因此,当对话框附加到
活动
时,您将知道创建它的
活动的实例

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;
        }
}
如果需要为对话框使用自己的自定义布局,请在
onCreateView
中展开布局,然后删除
onCreateDialog
。但是在
onCreateView
中添加单击侦听器,就像我在
onCreateDialog

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_dialog, container, false);
    return view;
}
然后,在
活动中
需要实现一个
界面
来处理
对话框中的操作

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
        }
}
最后,在需要时显示
活动中的
对话框,如下所示

    GeneralDialogFragment generalDialogFragment =
        GeneralDialogFragment.newInstance("title", "message");
    generalDialogFragment.show(getSupportFragmentManager(),"dialog");
希望这有帮助。我确信这种方法是一种优化方法,但也可能有不同的方法

请尝试以下代码:

呼叫方式

new CustomDialog().makeDialog(Activity.this,"pass value from diffrent-2 ");
类自定义对话框

public class CustomDialog
{

    public void makeDialog(Context con, String value)
    {
        final DialogTwoOptions dialog = new DialogTwoOptions(con);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.ur_xml);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        // set the custom dialog components - text, image
        // and button
        dialog.setCanceledOnTouchOutside(false);
        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
                if (value.equals("1"))
                {
                }
                else if (value.equals("1"))
                {
                }
                // do more condition
            }
        });

        no.setOnClickListener(new Button.OnClickListener()
        {
            public void onClick(View v)
            {
                dialog.dismiss();
                // Do something
                if (value.equals("1"))
                {
                }
                else if (value.equals("1"))
                {
                }
                // do more condition
            }
        });

        dialog.show();
    }
}

}我遇到了像你这样的问题。stackoverflow中的所有内容都不符合我的要求。所以我创建了自己的对话框类,它可以像AlertDialog.Builder类一样使用

在我的dialogxml.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>
要使用此警报类,只需使用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中调用dismise()函数。我希望这能对你有所帮助。让我知道这是不是你想要的。您可以根据需要在dialogxml.xml中更改布局。

我已经用了一段时间了。 在活动内调用alert对话框,其中alertDialog是名为Misc的类中的静态函数:

    Misc.alertDlg(this, "Confirm", "Delete the file?", "Yes", null, "Cancel",
                    (DialogInterface dialog, int which) -> {
                        if(which == Misc.BTN_POS)
                            deleteYourFile()
                    });
}
static public void alertDlg(Context context, String title, String msg, String btnPos, String btnNeutral, String btnNeg, DialogInterface.OnClickListener ocListener) {
    Builder db = new AlertDialog.Builder(context);
    db.setTitle(title);
    db.setMessage(msg);
    if (btnPos != null) db.setPositiveButton(btnPos, ocListener);
    if (btnNeutral != null) db.setNeutralButton(btnNeutral, ocListener);
    if (btnNeg != null) db.setNegativeButton(btnNeg, ocListener);
    db.setIcon(android.R.drawable.ic_dialog_alert);
    db.show();
}
fun alertDlg(context: Context, title: String, msg: String, btnNeg: String?, btnNeutral: String?, btnPos: String?,
             onClickCallback: (which: Int) -> Unit) {
    val ocListener = DialogInterface.OnClickListener() {dialog, which ->
        onClickCallback(which)
    }
    val db = AlertDialog.Builder(context)
    db.setTitle(title)
    db.setMessage(msg)
    if (btnPos != null) db.setPositiveButton(btnPos, ocListener)
    if (btnNeutral != null) db.setNeutralButton(btnNeutral, ocListener)
    if (btnNeg != null) db.setNegativeButton(btnNeg, ocListener)
    db.setIcon(android.R.drawable.ic_dialog_alert)
    db.show()
}
以及警报对话框函数(称为Misc的类中的静态函数:

    Misc.alertDlg(this, "Confirm", "Delete the file?", "Yes", null, "Cancel",
                    (DialogInterface dialog, int which) -> {
                        if(which == Misc.BTN_POS)
                            deleteYourFile()
                    });
}
static public void alertDlg(Context context, String title, String msg, String btnPos, String btnNeutral, String btnNeg, DialogInterface.OnClickListener ocListener) {
    Builder db = new AlertDialog.Builder(context);
    db.setTitle(title);
    db.setMessage(msg);
    if (btnPos != null) db.setPositiveButton(btnPos, ocListener);
    if (btnNeutral != null) db.setNeutralButton(btnNeutral, ocListener);
    if (btnNeg != null) db.setNegativeButton(btnNeg, ocListener);
    db.setIcon(android.R.drawable.ic_dialog_alert);
    db.show();
}
fun alertDlg(context: Context, title: String, msg: String, btnNeg: String?, btnNeutral: String?, btnPos: String?,
             onClickCallback: (which: Int) -> Unit) {
    val ocListener = DialogInterface.OnClickListener() {dialog, which ->
        onClickCallback(which)
    }
    val db = AlertDialog.Builder(context)
    db.setTitle(title)
    db.setMessage(msg)
    if (btnPos != null) db.setPositiveButton(btnPos, ocListener)
    if (btnNeutral != null) db.setNeutralButton(btnNeutral, ocListener)
    if (btnNeg != null) db.setNegativeButton(btnNeg, ocListener)
    db.setIcon(android.R.drawable.ic_dialog_alert)
    db.show()
}
但我最近把它改成了kotlin。 调用警报对话框(在Kotlin中):

和警报对话框函数(对象中名为Misc的函数):


我还使用了类似的方法来显示文本输入对话框。

但它不是一个具有自定义布局的自定义对话框。AlertDialog的默认主题非常难看。Libin,这确实是一个好主意,但并不通用。我的意思是,setPositiveButton和setNegativeButton的onClick事件可以更改。想象一下,我有10个对话框确定相同,但取决于我单击“是”时活动/屏幕的位置在所有这些活动中都会有所不同。好的。我会更新答案。你对Dialog Fragment满意吗?嗯,我想使用<3.0的android版本,但是,我觉得Dialog Fragment可以。我的意思是,迟早,我们会考虑>4.0的android版本。对不起,我需要一些时间来吃它,这有点难当我第一次看到它的时候…无论如何,这是我一直在寻找的一个很好的方法,通用代码。关键是将onClick事件链接到接口函数,并有一个基本对话框…非常明智。我还没有检查它,但我会接受它作为一个真正的答案。Thanks@Libin我如何在片段上使用它?这与Libin的想法相同。Onclick事件可以不可更改。我希望能够更改“是”或“否”事件的功能性,但我希望所有事件中都有相同的对话框。这就像覆盖onclick函数并在类中具有抽象函数……但我不知道如何获得它。为什么有人投了-1票?这是一个合理的问题。虽然代码受到赞赏,但它应该始终是我有一个附带的解释。这不一定很长,但它是预期的。这正是我所需要的…非常感谢!这对我来说很有用,但我不得不删除
requestWindowFeature(Window.FEATURE\u NO\u TITLE);
,因为它产生了一个错误这就是我想要的:如何将OnClickListener作为参数。谢谢!
static public void alertDlg(Context context, String title, String msg, String btnPos, String btnNeutral, String btnNeg, DialogInterface.OnClickListener ocListener) {
    Builder db = new AlertDialog.Builder(context);
    db.setTitle(title);
    db.setMessage(msg);
    if (btnPos != null) db.setPositiveButton(btnPos, ocListener);
    if (btnNeutral != null) db.setNeutralButton(btnNeutral, ocListener);
    if (btnNeg != null) db.setNegativeButton(btnNeg, ocListener);
    db.setIcon(android.R.drawable.ic_dialog_alert);
    db.show();
}
    Misc.alertDlg(this, "Confirm", "Delete the file?", "Yes", null, "Cancel"){
        which-> if(which == Misc.BTN_POS) deleteYourFile()
    }
fun alertDlg(context: Context, title: String, msg: String, btnNeg: String?, btnNeutral: String?, btnPos: String?,
             onClickCallback: (which: Int) -> Unit) {
    val ocListener = DialogInterface.OnClickListener() {dialog, which ->
        onClickCallback(which)
    }
    val db = AlertDialog.Builder(context)
    db.setTitle(title)
    db.setMessage(msg)
    if (btnPos != null) db.setPositiveButton(btnPos, ocListener)
    if (btnNeutral != null) db.setNeutralButton(btnNeutral, ocListener)
    if (btnNeg != null) db.setNegativeButton(btnNeg, ocListener)
    db.setIcon(android.R.drawable.ic_dialog_alert)
    db.show()
}