无法在AlertDialog中编辑EditText

时间:2017-04-03 09:41:40

标签: android android-edittext sharedpreferences alertdialog

我试图在第一次打开应用时从用户那里获取值。我正在膨胀AlertDialog以从用户获取值。我无法在EditText中输入任何文本,尽管我可以看到光标闪烁。

MainActivity中的代码

SharedPreferences sharedPreferences = getSharedPreferences("hasRunBefore", 0);
        boolean hasRun = sharedPreferences.getBoolean("hasRun", false);
        if (!hasRun) {
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putBoolean("hasRun", true);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            LayoutInflater layoutInflater = LayoutInflater.from(this);
            final View dialogView = layoutInflater.inflate(R.layout.alertdialog, null);
            final EditText editText = (EditText) dialogView.findViewById(R.id.alert_dialog_editText);
            builder.setView(dialogView)
                    .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            editText.requestFocus();
                            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
                            regNum = editText.getText().toString();
                        }
                    })
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            builder.show();
            edit.putString("registerNumber", regNum);
            edit.apply();
            TextView textView = (TextView) findViewById(R.id.regNum_textView);
            textView.setText(regNum);
        } else {
            //code if the app HAS run before
            TextView textView = (TextView) findViewById(R.id.regNum_textView);
            textView.setText(regNum);
        }

布局文件是

<?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="match_parent"
    android:id="@+id/alertDialog"
    >

    <TextView
        android:id="@+id/alert_dialog_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Your Register Number"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="33dp" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/alert_dialog_editText"
        android:hint="Type your register number here"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:layout_below="@+id/alert_dialog_textview"
         />

</RelativeLayout>

我做错了什么?

3 个答案:

答案 0 :(得分:1)

尝试使用此方法:

public void showEditTextDialog()
{

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater layoutInflater = LayoutInflater.from(this);

    final View dialogView = layoutInflater.inflate(R.layout.alertdialog, null);
    final EditText editText = (EditText) dialogView.findViewById(R.id.alert_dialog_editText);

    // Keyboard
    final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);

    // Auto show keyboard
    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean isFocused) {

            if (isFocused)
            {
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
            }
        }
    });

    builder.setView(dialogView)
            .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    regNum = editText.getText().toString();
                    Log.d("STACKOVERFLOW", "Registration number: " + regNum);

                    // Hide keyboard
                    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    // Hide keyboard
                    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

                    dialog.cancel();
                }
            });

    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

<强>输出:

enter image description here

答案 1 :(得分:1)

虽然Ferdous Ahamed发布的解决方案正在发挥作用,但我的代码首先没有任何问题。我在我的应用程序中调用了一些权限,但我没有正确配置它们。发生了什么,当打开应用程序时,重点放在权限对话框上。当我关闭该对话框时,焦点变为第二个权限对话框,我没有正确配置。因此焦点被发送到后台,无限地等待用户输入。

一旦我修复了权限,代码就开始工作了。感谢每一位帮助过我的人。

最初的权限代码:

    /* Ensures Bluetooth is available on the device and it is enabled. If not,
            displays a dialog requesting user permission to enable Bluetooth.*/
            if(!bluetoothAdapter.isEnabled())
            {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }

            /*Getting Fine Location Access from the User. For odd reasons, the device won't scan if the location access isn't granted by the user.*/
                if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                            android.Manifest.permission.ACCESS_FINE_LOCATION)) {

                        // Show an explanation to the user *asynchronously* -- don't block
                        // this thread waiting for the user's response! After the user
                        // sees the explanation, try again to request the permission.

                    } else {

                        // No explanation needed, we can request the permission.

                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                                MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);

                    }
                }

        //Getting READ_PHONE_STATE from the User.
            if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_PHONE_STATE)
                    != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        android.Manifest.permission.READ_PHONE_STATE)) {

                    // Show an explanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.

                } else {

                    // No explanation needed, we can request the permission.

                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{android.Manifest.permission.READ_PHONE_STATE},
                            MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);

                }
            }

我将代码更改为:(将权限合并为一个时间任务。应该早点完成此操作。我的不好。)

/*Getting Fine Location Access from the User. For odd reasons, the device won't scan if the location access isn't granted by the user.
        * Also getting the READ_PHONE_STATE permission in the same dialog*/
            if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE)
                    != PackageManager.PERMISSION_GRANTED )
            {
                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        android.Manifest.permission.ACCESS_FINE_LOCATION)) {

                    // Show an explanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.

                } else {

                    // No explanation needed, we can request the permission.

                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION , android.Manifest.permission.READ_PHONE_STATE},
                            MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
                }
            }

答案 2 :(得分:0)

试试这段代码:

// get yourView.xml view
                LayoutInflater li = LayoutInflater.from(context);
                View promptsView = li.inflate(R.layout.yourView, null);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);

                // set prompts.xml to alertdialog builder
                alertDialogBuilder.setView(promptsView);

                final EditText userInput = (EditText) promptsView
                        .findViewById(R.id.editTextDialogUserInput);

                // set dialog message
                alertDialogBuilder
                    .setCancelable(false)
                    .setPositiveButton("OK",
                      new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                        // get user input and set it to result
                        // edit text
                        result.setText(userInput.getText());
                        }
                      })
                    .setNegativeButton("Cancel",
                      new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                        dialog.cancel();
                        }
                      });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();