Jak mogę przekazać wartości między dialogiem a aktywnością?

Proszę użytkownika o wpis w oknie dialogowym:

package com.android.cancertrials;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class CustomDialog extends Dialog  {


    private String name;
//    private ReadyListener readyListener;
     public static EditText etName;
     public String zip;

    public CustomDialog(Context context, String name) {
        super(context);
        this.name = name;
//        this.readyListener = readyListener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mycustomdialog);
        setTitle("Enter the Zip Code ");
        Button buttonOK = (Button) findViewById(R.id.ok);
        buttonOK.setOnClickListener(new OKListener());
        etName = (EditText) findViewById(R.id.EditZip);
    }

    private class OKListener implements android.view.View.OnClickListener {
        @Override
        public void onClick(View v) {
//            readyListener.ready(String.valueOf(etName.getText()));
            CustomDialog.this.dismiss();
        }
    }


}

Gdy użytkownik trafi OK, Jak mogę przekazać wartość wpisaną w polu tekstowym z powrotem do zmiennej członkowskiej w aktywności, która ją uruchomiła?

Author: Sheehan Alam, 2010-11-25

2 answers

Możesz to zrobić na różne sposoby... w rzeczywistości, jeśli Twoje okno dialogowe ma tylko przycisk" OK " do odrzucenia, dlaczego po prostu nie utworzysz niestandardowego okna dialogowego przy użyciu klasy AlertDialog.Builder zamiast podklasowania Dialog?

W każdym razie... Załóżmy, że masz dobre powody, aby zrobić to tak, jak to zrobiłeś. W takim razie użyłbym obserwatora. Coś takiego:
public class CustomDialog extends Dialog  {


    private String name;
     public static EditText etName;
     public String zip;
    OnMyDialogResult mDialogResult; // the callback

    public CustomDialog(Context context, String name) {
        super(context);
        this.name = name;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // same you have
    }

    private class OKListener implements android.view.View.OnClickListener {
        @Override
        public void onClick(View v) {
            if( mDialogResult != null ){
                mDialogResult.finish(String.valueOf(etName.getText()));
            }
            CustomDialog.this.dismiss();
        }
    }

    public void setDialogResult(OnMyDialogResult dialogResult){
        mDialogResult = dialogResult;
    }

    public interface OnMyDialogResult{
       void finish(String result);
    }
}

O Twojej aktywności:

CustomDialog dialog;
// initialization stuff, blah blah
dialog.setDialogResult(new OnMyDialogResult(){
    public void finish(String result){
        // now you can use the 'result' on your activity
    }
});

Czytając Twój kod wydaje się, że już próbowałeś czegoś podobnego.

Edit: doing it the easy way

Nadal możesz używać swojego mycustomdialog układu. I tak byś użył AlertDialog.Builder:

LayoutInflater inflater = LayoutInflater.from(YourActivity.this);
final View yourCustomView = inflater.inflate(R.layout.mycustomdialog, null);

final TextView etName = (EditText) yourCustomView.findViewById(R.id.EditZip);
AlertDialog dialog = new AlertDialog.Builder(YourActivity.this)
    .setTitle("Enter the Zip Code")
    .setView(yourCustomView)
    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            mSomeVariableYouHaveOnYourActivity = etName.getText().toString();
        }
    })
    .setNegativeButton("Cancel", null).create();
dialog.show();
 69
Author: Cristian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-11-25 18:25:30

Osiągam to poprzez nadawanie z [dialog] do [aktywność] .

Pierwsze przekazanie aktywności do funkcji:

public class DialogFactory {

    public static AlertDialog addSomeDialog(Activity activity) {
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                  if (SOMETHING_IS_TRUE) {

                      // prepare your parameters that need to be sent back to activity
                      Intent intent = new Intent(IntentAction.INTENT_ADD_TASK);
                      intent.putExtra(IntentConst.PARAM_A, aInput);
                      intent.putExtra(IntentConst.PARAM_B, bInput);
                      activity.sendBroadcast(intent);

                      Toast.makeText(activity, "Something is TRUE!", Toast.LENGTH_SHORT).show();
                  } else {
                      Toast.makeText(activity, "Something NOT TRUE!", Toast.LENGTH_SHORT).show();
                  }
            }
        });
    }
}

Wywołanie powyższej funkcji po kliknięciu jakiegoś menu opcji lub przycisku w Twojej aktywności.

Następnie przygotuj swoją aktywność, aby otrzymać intencję za pomocą BroadcastReceiver w aktywności:

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() == IntentAction.INTENT_ADD_TASK) {
             // Do whatever you want to refresh the layout or anything in the activity
             // or even ask fragments inside to act upon it.
             .....
        }
    }
};

Nie zapomnij zarejestrować i wyrejestrować odbiornika:

@Override
protected void onPause() {
    unregisterReceiver(mReceiver);
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(mReceiver, new IntentFilter(IntentAction.INTENT_ADD_TASK));
}
 1
Author: Robert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-24 07:15:17