Android:如何定义多个活动访问的对话框片段?

时间:2015-05-04 17:46:27

标签: android android-fragments android-activity

我有一个Activity1,它显示了一个自定义的dialogfragment- ExampleDialog。我已经为dialogfragment实现了一个侦听器SubmitDialogListener,以使用onSubmit()与活动进行通信。在onSubmit()中,我正在显示一些其他的dialogfragment。我的问题是,如果我从Activity2显示相同的ExampleDialog片段,Activity2应该实现SubmitDialogListener接口并再次在Activity2中实现onSubmit()方法吗?或者有更好的方法来定义onSubmit()方法吗?

import android.support.v4.app.DialogFragment;
// ...   
public class Activity1 extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
  ......
  showDialog();
}

private void showDialog() {
  FragmentManager fm = getSupportFragmentManager();
  ExampleDialog exDialog = ExampleDialog.newInstance("Some Title");
  exDialog.show(fm, "fragment_edit_name");
}

@Override
public void onSubmit() {
//open new fragments
}
}

public class ExampleDialog extends DialogFragment implements SubmitDialogListener {

public interface SubmitDialogListener {
    void onSubmit();
}

public ExampleDialog() {
    // Empty constructor required for DialogFragment
}

public static ExampleDialog newInstance(String title) {
    ExampleDialog frag = new ExampleDialog();
    Bundle args = new Bundle();
    args.putString("title", title);
    frag.setArguments(args);
    return frag;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_edit_name, container);
    .........

   Button button = (Button) v.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

         SubmitDialogListener listener = (SubmitDialogListener) getActivity();
        listener.onSubmit();
        dismiss();
        }
    });

    return view;
}
}

1 个答案:

答案 0 :(得分:0)

在这种情况下,Activity应该实现SubmitDialogListener而不是Dialog Fragment,如下所示:

public class Activity1 extends ActionBarActivity implements SubmitDialogListener {

  @Override 
  public void onSubmit() { 
    //open new fragments 
  }
}

如果您想在多个活动中使用相同的对话框片段,通常最好在单独的类文件中创建它。