Android - how can I get Activity to enter text from a dialog

I thought it would be easy, but it eluded me. I have an Activity that displays a custom dialog box that allows the user to enter text, and then has an OK and Cancel button. I show it with show (). But I can’t understand how to return the value from the dialog.

I use a custom dialog because it does some text input validation. I think I could change it to get from Activity, and then display it using startActivityForResult, but at least based on my old days of window programming, I thought it would be easy to get the user-entered value from the Android dialog box.

I don't like any type of callback or listening mechanism?

I even tried this as a simple solution, but did not allow me to assign the value (1) if its modifier is not set to final, and then (2) if I say “ok” to make it final, it will not let me assign because "the final value of a local variable cannot be assigned because it is defined in the enclosing type"

    String value;

    final EditText input = (EditText)findViewById(R.id.theText); 

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(input);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() 
    {
        public void onClick(DialogInterface dialog, int whichButton) 
        {
            value = input.getText().toString();
            dialog.dismiss();
        }
    });
    builder.show();

[EDIT updated to solve] =============================

The main thing that I finished is to add the ability to pass a handler in a dialog box. In the dialog class, I added:

   private Handler clientHandler = null;

   public void AddHandler(Handler client)
   {
      this.clientHandler = client;
   }

And update the OK button OK:

   /**
    * The user pressed the OK button
    * @param v
    */
   public void okClick(View v)
   {
      // save the entered string
      this.tag = this.tagEditText.getText().toString();

      if ( null != this.clientHandler )
      {
         // Notify the client to update itself
         this.clientHandler.sendMessage( clientHandler.obtainMessage());
      }

      cancel();
   }

Then in Activity onCreate (), which displays the Added dialog:

 tagDialog = new tagDialog(this); 

 tagHandler = new Handler() 
 {
    @Override
    public void handleMessage(Message msg) 
    {
       tag = tagDialog.tag;               
    }
 };

 tagDialog.AddHandler(tagHandler);
+3
source share
3 answers

, . getMessage(), Message object, .

+1

, onClickListener Dialog. dialog.findViewById(), , - ( ), Activity .

+2

If I don’t miss something here, will there be a static string?

+2
source

Source: https://habr.com/ru/post/1779445/


All Articles