Android 通过一系列片段传递侦听器?
我希望能够定义一个监听器(一个活动、片段等),并能够在决定最终调用回调之前通过任意数量的嵌套片段传递它。这样它就可以调用Android 通过一系列片段传递侦听器?,android,android-fragments,android-activity,callback,listener,Android,Android Fragments,Android Activity,Callback,Listener,我希望能够定义一个监听器(一个活动、片段等),并能够在决定最终调用回调之前通过任意数量的嵌套片段传递它。这样它就可以调用callback.someFunction(),而不需要知道回调所附加的活动或片段 然而,现在似乎没有好的方法通过一堆片段来发送侦听器。我最初考虑将其传递给构造函数,但在配置更改(如屏幕旋转)时,侦听器引用将被清空 然后我考虑了onAttach()方法,但这些方法只允许您访问基本活动的上下文,这也不一定满足我的要求 我还考虑过通过newInstance()传递侦听器(这通常是将
callback.someFunction()
,而不需要知道回调所附加的活动或片段
然而,现在似乎没有好的方法通过一堆片段来发送侦听器。我最初考虑将其传递给构造函数,但在配置更改(如屏幕旋转)时,侦听器引用将被清空
然后我考虑了onAttach()
方法,但这些方法只允许您访问基本活动的上下文
,这也不一定满足我的要求
我还考虑过通过newInstance()
传递侦听器(这通常是将传递的参数保存到片段中的方式,因为getArguments()
的内容通过捆绑包保存配置更改),但是我在参数Bundle
中找不到保存侦听器的好方法
我能做什么?当发生配置更改时,或者当重新创建活动并恢复其实例状态时,您应该重新创建所有内容……这与此相同
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acitivyt_layout);
if(savedInstanceState != null){
//1. restore instance state here
savedInstanceState.getString("whatever");
//2. try to find the fragment
Fragment f = getSupportFragmentManager().findFragmentByTag("FRAGMENT TAG");
//3. make sure the fragment is correctly set up if already loaded
if(f != null){
((ConcreteFragmentType)f).setListener(your_listener);
//bring the fragment to the front or show it using the fragment manager
}
//4. or else add a brand-new instance
else{
ConcreteFragmentType c = ConcreteFragmentType.newInstance();
c.setListener(your_listener);
getSupportFragmentManager().beginTransaction()
.add(R.id.fragmentContainer, c)
.commit();
}
}
}
您应该做的是在发生配置更改或重新创建活动并恢复其实例状态时重新创建所有内容…这与此相同
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acitivyt_layout);
if(savedInstanceState != null){
//1. restore instance state here
savedInstanceState.getString("whatever");
//2. try to find the fragment
Fragment f = getSupportFragmentManager().findFragmentByTag("FRAGMENT TAG");
//3. make sure the fragment is correctly set up if already loaded
if(f != null){
((ConcreteFragmentType)f).setListener(your_listener);
//bring the fragment to the front or show it using the fragment manager
}
//4. or else add a brand-new instance
else{
ConcreteFragmentType c = ConcreteFragmentType.newInstance();
c.setListener(your_listener);
getSupportFragmentManager().beginTransaction()
.add(R.id.fragmentContainer, c)
.commit();
}
}
}
根据我的经验,这不是我想要的question@user6935095答案演示了如何在重新创建活动后恢复片段中的实例状态。我到底错过了什么?根据我的经验,这不是我想要的question@user6935095答案演示了如何在重新创建活动后恢复片段中的实例状态。我到底错过了什么?