2014-01-31 2 views
0

Я вызываю метод ShowDialog в своей деятельности. У меня есть список имен, поэтому я буду зацикливаться на этом списке имен, и для каждого имени я получу его числа. Некоторые имена могут иметь только число, а некоторые другие могут иметь больше. Если имя больше, чем число, я покажу другое диалоговое окно, в котором вам предлагается выбрать нужные вам номера.Android - Диалог внутри другого диалога - Как узнать, когда они оба закончили вызывать?

Когда все имена имеют только номер, это легко, я называю dialog.dismiss, затем SendSMS (ListOfNumbers) и, наконец, закончить():

ShowDialog(); 
SendSMS(listOfNumbers); 
finish(); 

Однако проблема возникает, когда пользователи имеют несколько номеров , Я не могу найти способ сообщить, когда процесс завершится. Метод

ShowDialog():

protected void ShowDialog() { 

    final Dialog dialog = new Dialog(ContactsPicker.this); 
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
    dialog.setContentView(R.layout.alert_dialog); 

    final CheckBox cbE = (CheckBox) dialog.findViewById(R.id.checkBoxEmail); 
    final CheckBox cbN = (CheckBox) dialog.findViewById(R.id.checkBoxNumber); 

    Button button = (Button) dialog.findViewById(R.id.button1); 
    button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      String names = ""; 
      String names1 = ""; 
      String names2 = ""; 

      if (cbN.isChecked()) { 
       //Send invitations through SMS 
       //List<String> numbers = new ArrayList<String>(); 
       String number = ""; 
       List<String> usernumbers = new ArrayList<String>(); 

       //Fill names string to send it back 
       for (int i = 0; i < selected.size(); i++) { 
        //number = get_Number(contactName, getApplicationContext()); 

        usernumbers = getNumber(selected.get(i), getApplicationContext()); 

        //Toast.makeText(getApplicationContext(),"Usernumbers list size: "+usernumbers.size(),Toast.LENGTH_SHORT).show(); 

        if (usernumbers.size() == 1) { 
         selectedNumbers.add(usernumbers.get(0)); 
        } else if (usernumbers.size() > 1) { 
         //Show select number dialog 
         dialog.hide(); 
         showSelectNumberPopup(usernumbers); 
        } else { 
        } 
        //dialog.show(); 
       } 
      } 

      if (cbE.isChecked()) { 
       //Send invitations through e-mail 
       List<String> emails = new ArrayList<String>(); 
       String email = ""; 

       for (String contactName : selected) { 
        email = get_Email(contactName, getApplicationContext()); 
        emails.add(email); 
        names2 += contactName + ","; 
       } 

       //showToast("Send E-mail Checked"); 
       sendEmail(emails); 
      } 
     } 
    }); 
} 

И showSelectNumberPopup метод:

protected void showSelectNumberPopup(List<String> usernumbers) { 
    LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View view = inflater.inflate(R.layout.alert_dialog_select_number, null); 
    // vi = LayoutInflater.from(getBaseContext()).inflate(R.layout.alert_dialog_select_number,null); 
    //View view = (View)getLayoutInflater().inflate(R.layout.alert_dialog_select_number, null); 
    dialogLV = (ListView) view.findViewById(R.id.list_select_number); 
    dialogLV.setAdapter(new SelectNumberDialogListAdapter(getApplicationContext(), usernumbers)); 
    dialogLV.setItemsCanFocus(false); 
    dialogLV.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 

    dialogLV.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) { 
      String selectedFromList = (String) (dialogLV.getItemAtPosition(myItemInt)); 
      cbSelectedNumber = (CheckBox) myView.findViewById(R.id.checkBoxNumber); 
      if (selectedNumbers.contains(selectedFromList)) { 
       selectedItemCB.setChecked(false); 
       selectedNumbers.remove(selectedFromList); 
       //Toast.makeText(getApplicationContext(), "Removed From SELECTED: " + selectedFromList, Toast.LENGTH_SHORT).show(); 
      } else { 
       selectedItemCB.setChecked(true); 
       selectedNumbers.add(selectedFromList); 
       //Toast.makeText(getApplicationContext(), "Added To SELECTED: " + selectedFromList, Toast.LENGTH_SHORT).show(); 
      } 
     } 
    }); 

    final Dialog dialog = new Dialog(ContactsPicker.this); 
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
    dialog.setContentView(view); 
    //Toast.makeText(getApplicationContext(),"GOT IN THE SECOND POPUP",Toast.LENGTH_SHORT).show(); 
    Button button = (Button) dialog.findViewById(R.id.button1); 
    button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      dialog.dismiss(); 
     } 
    }); 
    dialog.show(); 
    if (names1 != "") 
     names = names1; 
    else if (names2 != "") 
     names = names2; 
    else { 
     for (String contactName : selected) { 
      names += contactName + ","; 
     } 
    } 
    names = names.substring(0, names.lastIndexOf(",")); 
    //Set data to send it back to PickNamesActivity 
    Intent data = new Intent(); 
    //---set the data to pass back--- 
    data.setData(Uri.parse(names)); 
    setResult(RESULT_OK, data); 
    //finish(); 
    //sendSMS(selectedNumbers); 
    //finish(); 
    dialog.show(); 
} 
+0

Вы можете использовать метод dialog.isShowing(), чтобы проверить, видимо ли оно или отклонено. –

+0

Второе диалоговое окно может быть вызвано несколько раз, так как это должно помочь? – Hussain

ответ

0

TL; DR: Use an interface

Что может оказаться проще для вас, чтобы создать два (внутренний) Диалоговые классы, которые расширяют DialogFragment и вызывают их с помощью new FirstDialog().show(). Переместите связанный код в эти диалоги. Например:

private class FirstDialog extends DialogFragment { 


    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 

     View view = getLayoutInflater().inflate(R.layout.alert_dialog, null); 
     final CheckBox cbE = (CheckBox)view.findViewById(R.id.checkBoxEmail); 
     final CheckBox cbN = (CheckBox)view.findViewById(R.id.checkBoxNumber); 

     return new AlertDialog.Builder(this) 
       .setPositiveButton("Text here", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         //Put your on click stuff here 
        } 
       }).create(); 

    } 

} 

private class SecondDialog extends DialogFragment{ 

    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 

     View view = getLayoutInflater().inflate(R.layout.alert_dialog_select_number, null); 
     dialogLV = (ListView)view.findViewById(R.id.list_select_number); 
     dialogLV.setAdapter(new SelectNumberDialogListAdapter(getApplicationContext(),usernumbers)); 
     dialogLV.setItemsCanFocus(false); 
     dialogLV.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
     dialogLV.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) { 

       String selectedFromList = (String) (dialogLV.getItemAtPosition(myItemInt)); 
       cbSelectedNumber = (CheckBox)myView.findViewById(R.id.checkBoxNumber); 

       if (selectedNumbers.contains(selectedFromList)) { 
        selectedItemCB.setChecked(false); 
        selectedNumbers.remove(selectedFromList); 
        //Toast.makeText(getApplicationContext(), "Removed From SELECTED: " + selectedFromList, Toast.LENGTH_SHORT).show(); 

       } else { 
        selectedItemCB.setChecked(true); 
        selectedNumbers.add(selectedFromList); 
        //Toast.makeText(getApplicationContext(), "Added To SELECTED: " + selectedFromList, Toast.LENGTH_SHORT).show(); 
       } 

      } 
     }); 

     return new AlertDialog.Builder(this) 
       .setView(view) 
       .setPositiveButton("Text here", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         //What happens when the button is clicked 
        } 
       }).create(); 



    } 

не был уверен, что весь код сделал или как ваши диалоги были созданы, но, надеюсь, с этой базы вы можете поместить в остальной части материала. Когда вы хотите получить что-то из своего второго диалога, вы можете добавить к нему интерфейс, вызывая метод внутри вашей Activity, который будет делать все, что ему нужно. Here's an Android Developer link to help you with that.

+0

Спасибо за это. Это информативно. У меня есть решение, и я отправлю его позже, когда я убеждаюсь, что он работает на 100%. – Hussain

Смежные вопросы