我有一个Activity和一个简单的片段,我尝试使用Bundle将数据传递给片段,但是bundle总是为null。 我无法弄清问题是什么?!
这是我的Activity类
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentA fragmentA =new FragmentA();
Bundle bundle=new Bundle();
bundle.putString("name","Ahmed Ezzat");
fragmentA.setArguments(bundle);
}
public void showFragment(View view) {
FragmentA fragmentA=new FragmentA();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.dumper,fragmentA,"fragment A");
transaction.commit();
}
}
这是我的片段类
public class FragmentA extends Fragment {
TextView textView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_a,container,false);
textView= (TextView) view.findViewById(R.id.tv_fragment);
Bundle bundle = this.getArguments();
String name = bundle.getString("name");
if (name!=null){
textView.setText(name);}
return view;
}
}
任何帮助?
答案 0 :(得分:0)
您从未在position: absolute; bottom: 0;
方法中调用setArguments
。
showFragment
方法中的片段从未使用过。
您可以尝试使用以下代码
onCreate
答案 1 :(得分:0)
您可以在构建片段时将数据传递给片段,然后将其传递给事务。
public class FragmentA extends Fragment {
TextView textView;
String message;
public FragmentA(String message){
this.message = message;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_a,container,false);
textView= (TextView) view.findViewById(R.id.tv_fragment);
textView.setText(message);
return view;
}
当附加时,你只需在构造函数中传递它。