多个DialogFragment事件回调 - 如何判断要更新的片段?

时间:2017-09-06 19:46:01

标签: android android-fragments android-dialogfragment android-lifecycle

这是我的情况。我有一个片段,上面有两个按钮。当您点击任一按钮时,会出现merged.fastq 32 14824945 1992856 1576607 2413263 8756583 33 58619575 1415093 3274505 5499169 48070172 test.fastq 34 13018196 1047476 903554 1695778 9296236 ,其中包含带有确定/取消按钮的单个DialogFragment。两个按钮都打开相同的EditText,但输入DialogFragment的数据需要保持独立。

我最近开始从Android文档seen here实现片段事件回调模式,但遇到了一个问题 - 我有两个按钮使用相同的事件回调,我不知道如何区分用户有哪一个刚刚完成使用。因此,以文档为例,我可以从同一屏幕上的两个按钮打开EditText,但需要根据我点击的按钮不同地处理结果。

在我的片段中:

FragmentA

在我的Activity中,它实现了OnEditNameListener:

public static class FragmentA extends DialogFragment {
  public interface OnEditNameListener {
    public void onPositiveButtonClicked(String newName);
  }
}

@Override
public void onAttach(Context context){
    super.onAttach(context);
    try {
        mListener = (OnEditNameListener ) context;
    }
    catch (ClassCastException e) {
        throw new ClassCastException(context.toString() + " must implement OnEditNameListener ");
    }
}

目前,两个回调都使用来自button1.setOnClickListener(new OnClickListener(){ @Override public void onClick(View view) { (new EditNameDialog.Builder()) .setTitle(getContext().getString(R.string.title)) .setValue(currentText) .show(mParentFragmentActivity.getSupportFragmentManager()); } }); button2.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { (new EditNameDialog.Builder()) .setTitle(getContext().getString(R.string.title2)) .setValue(currentText2) .setInputType(InputType.TYPE_CLASS_NUMBER) .show(mParentFragmentActivity.getSupportFragmentManager()); } }); @Override public void onPositiveButtonClicked(String newName) { ... //does stuff with the name. //Currently no way to determine whether this came from button1 or button2. } 的输入触及相同的OnPositiveButtonClicked方法,但我不知道如何确定它来自哪两个按钮。

1 个答案:

答案 0 :(得分:1)

首先,您必须向onPositiveButtonClicked(String name,int buttonId)添加一个参数,并根据按下的按钮传递给FragmentA一个参数:

FragmentA fragment=new FragmentA();
 Bundle args = new Bundle();
 args.putInt("buttonId", 1 or 2);
 fragment.setArguments(args);
//open the fragment from the activity

然后在FragmentA onCreate方法中尝试:

 int buttonId = getArguments().getInt("buttonId"); 

最后当按下正按钮时:

onPositiveButtonClicked(newName,buttonId)

<强>更新

更好的解决方案是在DialogFragment中创建一个setter并使用匿名接口,如:

(new EditNameDialog.Builder())
      .setTitle(getContext().getString(R.string.title))
      .setValue(currentText).setOnEditNameListener(new EditNameListener{
         @Override
          onPositiveButtonClicked(String newName){
          //handle action
          }
});

在DialogFragment中添加setter:

EditNameListener listener;
public DialogFragment setOnEditNameListener(EditNameListener listener){
   this.listener=listener;
 return this;
}