验证AlertDialog中EditText的值

时间:2017-03-10 07:58:00

标签: android android-edittext alertdialog

我有类似这样的问题: Android Dialog, keep dialog open when button is pressed

我阅读了所有建议的解决方案,并使用了@Kamen

中的解决方案

所以这是我的代码:

package com.ts.techassi.ts;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Techassi on 07.03.2017.
 */

public class PinInput extends DialogFragment {
    public final static String EXTRA_MESSAGE = "ts.techassi.ts.MESSAGE";
    Context context;
    View view;
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("Test for preventing dialog close");
        builder.setTitle("Test");

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

            }
        });

        final AlertDialog dialog = builder.create();
        dialog.show();
        //Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Boolean wantToCloseDialog = false;
                //Do stuff, possibly set wantToCloseDialog to true then...
                if(wantToCloseDialog)
                    dialog.dismiss();
                //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.

                Uri url = readUrl();
                // String ts_id = url.getLastPathSegment();
                final EditText pin = (EditText)view.findViewById(R.id.pin);

                String pinString = pin.getText().toString();

                try {
                    String response = new Http().execute().get();
                    // Log.i("test", response);
                    Log.i("StackOverflow", String.format("response: %s, pinString: %s", response, pinString));
                    if( pinString.equals("1234") ) {
                        Boolean isLauncher = isMyAppLauncherDefault();
                        if(isLauncher == true){
                            resetPreferredLauncherAndOpenChooser(context);
                        }
                    } else {
                        PinInput.this.getDialog().cancel();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("Test",e.toString());
                }
            }
        });

        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Boolean wantToCloseDialog = true;
                //Do stuff, possibly set wantToCloseDialog to true then...
                if(wantToCloseDialog)
                    dialog.dismiss();
                //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
            }
        });
        return dialog;
    }

    public Uri readUrl() {
        String fileDirectory = Environment.getExternalStorageDirectory()+"/dbDoorsign/url.txt";

        File file = new File(fileDirectory);

        StringBuilder text = new StringBuilder();
        ;

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;

            while ((line = br.readLine()) != null) {
                text.append(line);
            }
            br.close();
        }
        catch (IOException e) {

        }
        return Uri.parse(text.toString());
    }

    private boolean isMyAppLauncherDefault() {
        final IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
        filter.addCategory(Intent.CATEGORY_HOME);

        List<IntentFilter> filters = new ArrayList<IntentFilter>();
        filters.add(filter);

        final String myPackageName = getActivity().getPackageName();
        List<ComponentName> activities = new ArrayList<ComponentName>();
        final PackageManager packageManager = (PackageManager) getActivity().getPackageManager();

        packageManager.getPreferredActivities(filters, activities, null);

        for (ComponentName activity : activities) {
            if (myPackageName.equals(activity.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    public static void resetPreferredLauncherAndOpenChooser(Context context) {
        PackageManager packageManager = context.getPackageManager();
        ComponentName componentName = new ComponentName(context, FakeLauncherActivity.class);
        packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

        Intent selector = new Intent(Intent.ACTION_MAIN);
        selector.addCategory(Intent.CATEGORY_HOME);
        selector.putExtra(EXTRA_MESSAGE, "1");
        selector.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(selector);

        packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, PackageManager.DONT_KILL_APP);
    }

}

我真的认为这个解决方案可行,但在我的情况下,我没有。 所以我希望你能帮助我。谢谢!

1 个答案:

答案 0 :(得分:0)

自动关闭行为来自AlertDialog类 如果你想避免它,你可以使用常规对话框 由于您已经有了DialogFragment,因此可以覆盖onCreateView()而不是onCreateDialog()。这将创建一个常规对话框并将您的视图放入其中。请注意,如果你走这条路,你必须自己制作一个标题和按钮。

修改
没关系,您也可以通过在按钮本身上设置额外的OnClickListener来覆盖此行为。见https://stackoverflow.com/a/28282583/6151924