我有两个 Activity 和两个 fragment :detialActivity 和 detialActivityFragment、mainActivity 和 mainActivityFragment。 我如何在 detialActivityFragment 和 mainActivityFragment 之间传递数据。 当我尝试传递数据时显示异常:java.lang.NullPointerException 我做了界面:
public interface OnButtonPressListener {
public void onButtonPressed(String msg);
}
在类 mainActivityFragment 中:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
buttonListener = (OnButtonPressListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must
implement onButtonPressed");
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_main, container,
false);
listMovie = (GridView) root.findViewById(R.id.gridview_movie);
listMovie.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
buttonListener.onButtonPressed("hi");
}
});
return root;
}
内部类 detialActivityFragment:
void setMessage(String msg){
TextView txt=(TextView)root.findViewById(R.id.titleDetialMovie);
txt.setText(msg);
}
内部类 detialActivity:
@Override
public void onButtonPressed(String msg) {
DetialActivityFragment Obj=(DetialActivityFragment)
getSupportFragmentManager().findFragmentById(R.id.detialActivityFragment);
Obj.setMessage(msg);
}
最佳答案
你不应该这样调用方法。 而是将数据传递给 Fragment 的构造函数并在那里使用它。
关于android - 如何在两个 fragment 之间传递数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32137767/