我有一个回调接口。
public interface RowCallback {
void callOnRowAction(String action);
}
我的片段FragmentA
连接到ActivityA
,其中FragmentA
的定义如下:
class FragmentA extends Fragment implements RowCallback {
@Override
void callOnRowAction(String action) {
. . . Custom implementation . . .
}
... Other methods . . .
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mButton = view.findViewById(R.id.my_button);
mButton.setOnClickListener((view) -> {
// I want to pass the callback instance (which is FragmentA) to activity B.
Intent intent = new Intent(getActivity(), ActivityB.class);
. . . Some more intent initialisation. . .
startActivity(intent);
});
return view;
}
}
ActivityB源代码
public class ActivityB extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = createFragment(getIntent());
fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
}
}
private Fragment createFragment(Intent intent) {
FragmentB fragment = new FragmentB();
Bundle bundle = new Bundle();
. . . . initialise bundle . . .
// I want to pass the callback instance from the intent to the callback function.
// In this example, the callback instance would be an instance of fragment A.
fragment.setArguments(bundle);
return fragment;
}
}
在FragmentB实例中,我想在满足逻辑条件的情况下调用回调方法。我想在通过调用getActivity().finish();
调用了回调函数后返回到ActivityA / FragmentA。
我如何实现这样的目标?
答案 0 :(得分:1)
我将拆分答案:
如果您想一次回调:
OnclickListener
将调用他的活动(让我们说A)。 StartActivityForResult(intent)
进入活动B。OnclickListener
将
更新他的活动(B)。 onActivityResult
上捕获它。 如果您想多次回调:
LocalBroadcastManager
进行活动交流
Activity communication using LocalBroadcastManager 答案 1 :(得分:1)
要在执行后调用的片段中的实现函数
public void testCallBack(Callback callback) {
callback.callOnRowAction("callback");
}
在Activity类中实现
public void getCallBack() {
FragmentA.newInstance().testCallBack(new FragmentA.Callback() {
@Override
public void callOnRowAction(String action) {
//you can do something
}
});
}
如果要在函数启动时执行testCallBack方法,则可以在onCreate方法中调用它
答案 2 :(得分:0)
您可以在片段中添加
if(getParentFragment() instanceof Activity1)
((Activity1) getParentFragment()).setRowCallback(this);
else if(getParentFragment() instanceof Activity2)
((Activity2) getParentFragment()).setRowCallback(this);
该片段将自动调用其父活动的回调