我的活动中有这个界面。
public interface LogoutUser {
void logout();
}
我的片段实现了这个接口,所以在我的片段中,我有这个:
@Override
public void logout() {
// logout
}
在我的活动中我打电话
mLogoutUser.logout();
Where mLogoutUser
是 LogoutUser 接口类型。
我的问题是mLogoutUser
为空的对象。如何初始化它?
谢谢你!
正如我在评论中所说,我使用以下方法解决了这个问题onAttach
方法在我的片段中,但这样你必须在片段中声明回调字段(在本例中为 mLogoutUser ),并以这种方式初始化它:
public class MyFragment extends ListFragment {
LogoutUser mLogoutUser;
// Container Activity must implement this interface
public interface LogoutUser {
public void logout();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mLogoutUser = (LogoutUser) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement LogoutUser");
}
}
...
}
更多信息在与其他片段通信 http://developer.android.com/training/basics/fragments/communicating.html.
但如果您的情况是活动中声明的字段,您可以使用onAttachFragment
您的活动中的方法以这种方式初始化您的侦听器字段:
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
mLogoutUser = (LogoutUser) fragment;
}
此外,您还可以使用事件总线在片段和活动之间进行通信。一个选项是奥托图书馆 http://square.github.io/otto/,来自广场。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)