【发布时间】:2017-09-06 19:46:01
【问题描述】:
这是我的情况。我有一个片段,上面有两个按钮。当您点击任一按钮时,会出现一个DialogFragment,其中包含一个带有确定/取消按钮的EditText。两个按钮打开同一个DialogFragment,但输入到EditTexts的数据需要分开。
我最近开始实现 Android 文档 seen here 中的片段事件回调模式,但遇到了一个问题 - 我有两个按钮使用相同的事件回调,我不确定如何区分用户刚刚完成了哪一个使用。因此,以文档为例,我可以从同一屏幕上的两个按钮打开FragmentA,但需要根据我单击的按钮以不同方式处理结果。
在我的片段中:
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 ");
}
}
在我的 Activity 中,它实现了 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.
}
目前,两个回调都使用来自DialogFragment 的输入命中相同的 OnPositiveButtonClicked 方法,但我不知道如何确定这来自两个按钮中的哪一个。
【问题讨论】:
标签: android android-fragments android-dialogfragment android-lifecycle