Какая польза от этого кода в моем файле? - PullRequest
0 голосов
/ 12 декабря 2011

я подал заявку.И я хотел добавить лицензионное соглашение с конечным пользователем в мое приложение.Итак, я создал класс, чтобы сделать это ... во-первых, я использовал, чтобы показать свое лицензионное соглашение со встроенным AlertDialog Android.это работало нормально .. Затем я сделал свой собственный AlertDialog, а затем попытался показать ELUA в моем пользовательском диалоге.Теперь он работает нормально ... Файлы были похожи ...

//my Eula.java file...
//Gets the Eula file from assests folder...



 class Eula {

        private static final String ASSET_EULA = "EULA";
        private static final String PREFERENCE_EULA_ACCEPTED = "eula.accepted";
        private static final String PREFERENCES_EULA = "eula";

        static interface OnEulaAgreedTo {
            void onEulaAgreedTo();
        }

        static boolean show(final Activity activity) 
    {
            final SharedPreferences preferences = activity.getSharedPreferences(PREFERENCES_EULA,
                    Activity.MODE_PRIVATE);
            if (!preferences.getBoolean(PREFERENCE_EULA_ACCEPTED, false)) 
            {
                final CustomDialog.Builder builder = new CustomDialog.Builder(activity);
                builder.setTitle(R.string.app_name1);
                //builder.setCancelable(true);
                builder.setPositiveButton(R.string.eula_accept, new DialogInterface.OnClickListener() 
                {
                    public void onClick(DialogInterface dialog, int which) 
                    {
                        accept(preferences);
                        /*if(activity instanceof OnEulaAgreedTo)
                        {
                            ((OnEulaAgreedTo) activity).onEulaAgreedTo();   
                        }*/
dialog.dismiss();
                    }
                });
                builder.setNegativeButton(R.string.eula_refuse, new DialogInterface.OnClickListener() 
                {

                    public void onClick(DialogInterface dialog, int which) {
                        refuse(activity);
                    }
                });
                CharSequence s = readEula(activity);
                builder.setMessage(s.toString());
                builder.create().show();
                return false;
            }
            return true;
        }

        private static void accept(SharedPreferences preferences) {
            preferences.edit().putBoolean(PREFERENCE_EULA_ACCEPTED, true).commit();
        }

        private static void refuse(Activity activity) {
            activity.finish();
        }

        private static CharSequence readEula(Activity activity) {
            BufferedReader in = null;
            try {
                in = new BufferedReader(new InputStreamReader(activity.getAssets().open(ASSET_EULA)));
                String line;
                StringBuilder buffer = new StringBuilder();
                while ((line = in.readLine()) != null) buffer.append(line).append('\n');
                return buffer;
            } catch (IOException e) {
                return "";
            } finally {
                closeStream(in);
            }
        }
        private static void closeStream(Closeable stream) {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                }
            }
        }
    }

А потом у меня есть мой файл CustomDialog

//my CustomDialog.java file...
public class CustomDialog extends Dialog {
    private static final String ASSET_EULA = "EULA";

    public CustomDialog(Context context, int theme) {
        super(context, theme);
    }

    public CustomDialog(Context context) {
        super(context);
    }
    public static class Builder {

        private Context context;
        private String title;
        private String message;
        private String positiveButtonText;
        private String negativeButtonText;
        //private String cancelButtonText;
        private View contentView;

        private DialogInterface.OnClickListener 
                        positiveButtonClickListener,
                        negativeButtonClickListener;

        public Builder(Context context) {
            this.context = context;
        }

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

        public Builder setMessage(int message) {
            this.message = (String) context.getText(message);
            return this;
        }
        public Builder setTitle(int title) {
            this.title = (String) context.getText(title);
            return this;
        }

        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }
        public Builder setContentView(View v) {
            this.contentView = v;
            return this;
        }

        public Builder setPositiveButton(int positiveButtonText,
                DialogInterface.OnClickListener listener) {
            this.positiveButtonText = (String) context
                    .getText(positiveButtonText);
            this.positiveButtonClickListener = listener;
            return this;
        }

        public Builder setPositiveButton(String positiveButtonText,
                DialogInterface.OnClickListener listener) {
            this.positiveButtonText = positiveButtonText;
            this.positiveButtonClickListener = listener;
            return this;
        }

        public Builder setNegativeButton(int negativeButtonText,
                DialogInterface.OnClickListener listener) {
            this.negativeButtonText = (String) context
                    .getText(negativeButtonText);
            this.negativeButtonClickListener = listener;
            return this;
        }

        public Builder setNegativeButton(String negativeButtonText,
                DialogInterface.OnClickListener listener) {
            this.negativeButtonText = negativeButtonText;
            this.negativeButtonClickListener = listener;
            return this;
        }

        public CustomDialog create() {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // instantiate the dialog with the custom Theme
            final CustomDialog dialog = new CustomDialog(context, 
                    R.style.Dialog);
            View layout = inflater.inflate(R.layout.dialog, null);
            dialog.addContentView(layout, new LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            // set the dialog title
            ((TextView) layout.findViewById(R.id.title)).setText(title);
            // set the confirm button
            if (positiveButtonText != null) 
            {
                ((Button) layout.findViewById(R.id.positiveButton)).setText(positiveButtonText);
                if (positiveButtonClickListener != null) 
                {
                    ((Button) layout.findViewById(R.id.positiveButton)).setOnClickListener(new View.OnClickListener() 
                    {
                        public void onClick(View v) 
                        {
                            positiveButtonClickListener.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
                        }
                            });
                }
            } else {
                // if no confirm button just set the visibility to GONE
                layout.findViewById(R.id.positiveButton).setVisibility(
                        View.GONE);
            }
            // set the cancel button
            if (negativeButtonText != null) {
                ((Button) layout.findViewById(R.id.negativeButton))
                        .setText(negativeButtonText);
                if (negativeButtonClickListener != null) {
                    ((Button) layout.findViewById(R.id.negativeButton))
                            .setOnClickListener(new View.OnClickListener() {
                                public void onClick(View v) 
                                {
                                    negativeButtonClickListener.onClick(dialog, DialogInterface.BUTTON_NEGATIVE);
                                }
                            });
                }
            } else {
                // if no confirm button just set the visibility to GONE
                layout.findViewById(R.id.negativeButton).setVisibility(
                        View.GONE);
            }
            // set the content message
            if (message != null) {
                ((TextView) layout.findViewById(
                        R.id.message)).setText(message);
            } else if (contentView != null) {
                // if no message set
                // add the contentView to the dialog body
                ((LinearLayout) layout.findViewById(R.id.content))
                        .removeAllViews();
                ((LinearLayout) layout.findViewById(R.id.content))
                        .addView(contentView, 
                                new LayoutParams(
                                        LayoutParams.WRAP_CONTENT, 
                                        LayoutParams.WRAP_CONTENT));
            }
            dialog.setContentView(layout);
            return dialog;
        }

        public void dismiss() 
        {
            this.dismiss();
        }

        public void setCancelable(boolean b) {
            // TODO Auto-generated method stub
            this.setCancelable(true);
        }
    }
}

Atfirst, кнопка onClickfor setPositive для файла eula.javaбыло похоже на

public void onClick(DialogInterface dialog, int which) 
                {
                    accept(preferences);
                    if(activity instanceof OnEulaAgreedTo)
                    {
                        ((OnEulaAgreedTo) activity).onEulaAgreedTo();
                    }
                }

, он прекрасно работал для встроенного AlertDialog.но когда я изменил его в своем собственном диалоге, эта кодировка всегда приводит к ложному результату ...

Может кто-нибудь сказать мне, для чего предназначен этот код?

Ответы [ 2 ]

1 голос
/ 12 декабря 2011

Для исчезновения диалога вы должны использовать Dialog.dismiss().Вы можете закрыть диалоговое окно только в конце положительного поведения кнопки.

Когда вы нажимаете кнопку отказа, вы завершаете действие, и поэтому ваше диалоговое окно закрывается.

1 голос
/ 12 декабря 2011

Проблема может быть в следующем состоянии. проверьте экземпляр действия, соответствует ли оно условию?

if(activity instanceof OnEulaAgreedTo)
                    {
                        ((OnEulaAgreedTo) activity).onEulaAgreedTo();   
                    }
...