对于Android世界来说,这几乎是新事物,我遇到了在片段之间传递参数的问题.我需要它来设置标签导航菜单中特定标签的ID.
在我的MainActivity.java中,我正在创建TabFragment的新实例,然后像这样启动事务:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
mFragmentManager = getSupportFragmentManager();
...
Fragment fragment = TabFragment.newInstance(0);
fragmentTransaction(mFragmentManager, fragment);
...
}
哪里
private void fragmentTransaction(FragmentManager mFragmentManager, Fragment fragment) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView, fragment).commit();
}
(我将其封装在一种方法中,因为在其他地方也需要它.)
在我的TabFragment.java中,我编写了像这样的常规newInstance()方法:
public static TabFragment newInstance(int position) {
Log.d("POSITION", "newInstance: " + position);
TabFragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}
问题在于,留在TabFragment.java中,我的getArguments()调用返回了一个空指针,因为它看起来像我的saveInstanceState也为空.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int position;
try {
position = savedInstanceState.getInt(ARG_POSITION);
} catch (NullPointerException e) {
position = -1;
}
Log.d("BUNDLE", "position: " + position);
int position = getArguments().getInt(ARG_POSITION);
...
}
代码在getArguments()崩溃.
在评论该行时,我通过异常捕获发现捆绑包为空(位置= -1).
关于我做错什么的任何提示吗?
我一直在寻找类似的情况,但是我无法将这些解决方案应用于我的代码.
感谢您的任何帮助.
解决方法:
使用片段发送数据
try {
Bundle bundle = new Bundle();
bundle.putString("key","value"); // data that you want to send
LoginFragment fragment = new LoginFragment(); // Fragment that you want to call
fragment.setArguments(bundle);
FragmentTransaction fts = getSupportFragmentManager().beginTransaction();
fts.replace(R.id.fragmentHolder, fragment);
fts.addToBackStack(fragment.getClass().getSimpleName());
fts.commit();
}
catch (Exception e){
e.printStackTrace();
}
通过其他片段中的Bundle接收数据
try {
Bundle bundle = new Bundle();
String data = bundle.getString("key"); // Receive data through key
}
catch (Exception e){
e.printStackTrace();
}