Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a user String in a dialog popup

In my Android code, I inflate the GUI and store all the sub-elements in a different class. In that class, I want to add a method to read a user input from. I tried to follow something like in this link but no matter what I do, it boils down into copying a final value into a non final value. I though about creating another gui but couldn't fins a way to do so. Here is the method I have now:

private String setText(int id){
        AlertDialog.Builder alert = new AlertDialog.Builder(this.show);
        final EditText input = new EditText(this.show);
        alert.setView(input);
        String out;
        alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            //@Override
            public void onClick(DialogInterface dialog, int which) {
                Editable value = input.getText();
                out = value.toString();
                // TODO Auto-generated method stub

            }
        });

    }
}

Which I use to return a string into another method which set the value of the TextView.


I tried to do the following trick:

private String setText(){

    AlertDialog.Builder alert = new AlertDialog.Builder(this.show);
    final EditText input = new EditText(this.show);
    alert.setView(input);
    String out;
    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            input.setText("canceled");
        }
    });
    alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {


        }
    });
    alert.show();
    String toSend = input.getText().toString();
    this.maxT.setText(toSend);
    return toSend;

maxT is a TextView field. The app simply place an empty string. I figure that I should wait until the AlertDialog is closed, I'm searching for a way to do so.

like image 923
Yotam Avatar asked Jan 24 '26 08:01

Yotam


1 Answers

Just set the id of your View and reference it:

private String setText(int id){
    AlertDialog.Builder alert = new AlertDialog.Builder(this.show);
    EditText input = new EditText(this.show);
    input.setId("myInput");        
    alert.setView(input);
    String out;
    alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        //@Override
        public void onClick(DialogInterface dialog, int which) {
            EditText input = (EditText) dialog.findViewById("myInput");
            Editable value = input.getText();
            out = value.toString();               

        }
    });

}

}

View: setId() API

Dialogs onClick: onClick() API

like image 118
Blundell Avatar answered Jan 26 '26 21:01

Blundell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!