使EditText从NumberPicker获得输入

时间:2019-01-11 14:56:58

标签: java android

我正在尝试创建一个EditText字段,以便onClick打开numberPicker,以便用户可以输入数字。 这是我的代码:

tipET.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {

            final NumberPicker numberPicker = new NumberPicker(getContext());
            numberPicker.setMaxValue(1000);
            numberPicker.setMinValue(0);


            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setView(numberPicker);
            builder.setTitle("tip");
            builder.setPositiveButton("ok",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            Log.d(TAG, "TIP NUMBER IS:" + numberPicker.getValue());
                            num =  numberPicker.getValue();
                        }
                    });
            builder.setNegativeButton("cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.dismiss();
                        }
                    });
            builder.create();
            builder.show();

      }
    });
    tipET.setText(String.valueOf(num));

由于某些原因,在我输入另一个数字后,tipET文本保持不变,为什么?

也是我第一次单击EditText时,键盘会弹出,而仅在第二次单击时,我的NumberPicker打开,我该如何防止呢?

1 个答案:

答案 0 :(得分:0)

tipET.setText(String.valueOf(num));添加到num = numberPicker.getValue();下方的肯定按钮的onClick方法中,如下所示:

tipET.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {

        final NumberPicker numberPicker = new NumberPicker(getContext());
        numberPicker.setMaxValue(1000);
        numberPicker.setMinValue(0);


        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(numberPicker);
        builder.setTitle("tip");
        builder.setPositiveButton("ok",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Log.d(TAG, "TIP NUMBER IS:" + numberPicker.getValue());
                        num =  numberPicker.getValue();
                        // update the text of the EditText here
                        tipET.setText(String.valueOf(num));
                    }
                });
        builder.setNegativeButton("cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                    }
                });
        builder.create();
        builder.show();

  }
});