0

我有许多不同的状态,我需要根据这些状态以AlertDialog. 为每个警报创建一个单独的类简直太疯狂了。我现在拥有的是:

class FeedbackAlertDialog extends DialogFragment {
    private String message;
    private int action;

    FeedbackAlertDialog() {
    }

    FeedbackAlertDialog(String message, int action) {
        this.message = message;
        this.action = action;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        return new AlertDialog.Builder(getActivity())
                .setCancelable(false)
                .setTitle(message)
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        switch (action) {
                            case action: // It's impossible because the int should be final
                        }
                        startActivity(new Intent(getActivity(), MainActivity.class));
                    }
                }).show();
    }
}

问题是我不能使用switch,因为int应该是最终的。怎么想出这种情况?

4

3 回答 3

0

采用:

FeedbackAlertDialog.this.action

据我所知,这应该在开关中。

同样的方式用于访问更高级别的变量(简单模型中的通知设置器)。

在您的情况下,您必须首先进入根对象的范围(您的情况是 FeedbackAlertDialog)。

于 2012-07-17T14:40:38.713 回答
0

编辑 ::

在您的计算机系统上尝试这个简单的 java 演示:

public class CalcDemo {
    public static void main(String[] args) {
        int n1 = 6, n2 = 3;
        int opr = 1;
        MyMath math = new MyMath(n1, n2, opr);
        System.out.println("Answer :: "+math.getResult());
    }
}

class MyMath {
    int n1, n2, opr;

    public MyMath() {   }
    public MyMath(int n1, int n2, int opr) {
        this.n1 = n1;
        this.n2 = n2;
        this.opr = opr;
    }
    public int getResult() {
        //int ch = opr;
        switch (opr) {
        case 1: return n1-n2;
            //break;
        case 2: return n1+n2;
        default : System.out.println("Invalid Choice");
            break;
        }
        return 0;
    }
}

做一个技巧如下:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    return new AlertDialog.Builder(getActivity())
            .setCancelable(false)
            .setTitle(message)
            .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    final int action1 = action;  //  <---- ---  Try This
                    switch (action1) {  //  <--- ---  Use as This
                        case action1: // I THINK,  NOW  THIS  IS  POSSIBLE
                    }
                    startActivity(new Intent(getActivity(), MainActivity.class));
                }
            }).show();
}
于 2012-07-17T15:15:20.667 回答
0

这是不可能的,因为您需要在 switch 中使用常量。

于 2012-07-18T06:53:24.123 回答