【发布时间】:2017-10-05 00:48:10
【问题描述】:
我正在尝试将数据从活动发送到片段。 我没有将数据从片段发送到活动。除了在活动中实例化接口侦听器对象之外,我已经正确设置了所有内容。
public class Activity extends AppCompatActivity {
private FragmentInterface fragmentInterfaceListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This line below is actually in a button onClick()
fragmentInterfaceListener.sendDataMethod(dataToSend);
}
public interface FragmentInterface {
void sendDataMethod(SampleData sampleData);
}
}
然后在片段中,我有:
public static class CustomFragment extends Fragment implements Activity.FragmentInterface {
@Override
public void sendDataMethod(final SampleData sampleData) {
}
}
当我在按钮onClick() 中放入日志行时,单击按钮时会出现日志行。不,我不会将 sampleData 放入片段包中。是的,我需要通过接口发送数据。那么如何正确实例化Activity中的fragmentInterfaceListener对象呢?我在 Activity 或 CustomFragment 中是否遗漏了任何其他内容?
【问题讨论】:
-
你要问清楚。不要偷懒放代码
-
与其在活动中保留
FragmentInterface接口,不如在活动中保留CustomFragment片段。然后您可以在CustomFragment片段中声明公共方法,以便您的活动可以轻松使用这些方法。