我在一个活动中有多个片段,应该能够在它们之间传递数据。我已经使用教程来实现回调。我的 MainActivity 是我的片段类所在的外部类。此外,我有一个处理片段转换的 FragmentPagerAdapter。事情是这样的,Eclipse 不会让我为我的 MainActivity 外部类实现我的回调接口,它包含在片段之一中。
这是我的代码的结构:
public class MainActivity extends FragmentActivity **implements ConnectionFragment.dataCallback**{
//compiler error here:"ConnectionFragment cannot be resolved to a type"
//when i leave this out i get runtime error: "MainActivity java must
//implement dataCallback"
...
public class SectionsPagerAdapter extends FragmentPagerAdapter implements ConnectionFragment.dataCallback{
@Override
public void updateLog(View v, String line) {
DataFragment dataFrag = (DataFragment)getSupportFragmentManager().findFragmentByTag(DataFragment.class.getName());
if (dataFrag != null){
dataFrag.updateLog(v,line);
}
}
...
}
public static class ConnectionFragment extends Fragment {
...
public interface dataCallback{
public void updateLog(View v, String line);
}
dataCallback mCallback;
private static dataCallback dummyCallback=new dataCallback(){
@Override
public void updateLog(View v, String line){
}
};
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
try {
mCallback = (dataCallback)activity;
} catch (ClassCastException e){
throw new ClassCastException(activity.toString() + " must implement dataCallback");
}
}
}
public static class DataFragment extends Fragment implements ConnectionFragment.dataCallback{
public void updateLog(View v,String line){
TextView logTextView=(TextView)v.findViewById(R.id.log_view);
logTextView.append("\n"+line);
}
...
}
public static class GraphFragment extends Fragment {
...
}
}
ConnectionFragment 应该能够向 DataFragment 发送数据。
我感谢您的帮助!