2017-08-13 62 views
0

所以這是我的對話框類:如何從對話框類值傳遞給它的主機

public class SecondActivity extends DialogFragment { 

    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 
     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
     LayoutInflater inflater = getActivity().getLayoutInflater(); 

     builder.setView(inflater.inflate(R.layout.second, null)) 
       .setPositiveButton("Save", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int id) { 

        } 
       }) 
       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         dismiss(); 
        } 
       }); 
     return builder.create(); 
    } 
} 

在我的對話有哪些得到2串2個編輯文本。如果用戶按下保存按鈕,我想在MainActivity中使用這兩個字符串。我怎麼做?

+0

使用getActivity()返回什麼您的主機活動實例。如果在MainActivity中有一個方法setString1(...),可能((MainActivity)getActivity())。setString1(「text」)。 –

+0

這可能有所幫助:https://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents –

回答

0

的充氣方法返回一個視圖,您可以執行findViewById,如下所示:

@Override 
public Dialog onCreateDialog(Bundle savedInstanceState) { 
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
    LayoutInflater inflater = getActivity().getLayoutInflater(); 
    View v = inflater.inflate(R.layout.second, null); 
    EditView editView = (EditView)v.findById(R.id.your_edit_view); 
    builder.setView(v) 
      .setPositiveButton("Save", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int id) { 

       } 
      }) 
      .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        dismiss(); 
       } 
      }); 
    return builder.create(); 
} 
相關問題