我有两个片段.addfragment和控制片段。从addfragment我使用带有片段事务的bundle发送数据,然后在控制片段中,我想使用bundle获取数据,但我无法获取数据。所以请帮助我
这是我的片段事务的addfragment -
relaylist.setAdapter(adapter);
relaylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String, String> o = (HashMap<String, String>) relaylist.getItemAtPosition(position);
Log.e("ip: ", "> " + o.get("ip"));
Log.e("port: ", "> " + o.get("port"));
Log.e("uname: ", "> " + o.get("uname"));
Log.e("password: ", "> " + o.get("password"));
ControlFragment fragment = new ControlFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Bundle bundle = new Bundle();
bundle.putString("ip", o.get("ip"));
bundle.putString("port", o.get("port"));
bundle.putString("uname", o.get("uname"));
bundle.putString("password", o.get("password"));
Log.e("ip: ", "> " + o.get("ip"));
Log.e("port: ", "> " + o.get("port"));
Log.e("uname: ", "> " + o.get("uname"));
Log.e("password: ", "> " + o.get("password"));
fragment.setArguments(bundle);
transaction.replace(R.id.mainFrame, new ControlFragment() );
transaction.commit();
}
});
并且在控件片段中,我以这种方式获取数据......但我无法获取数据
public class ControlFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView= inflater.inflate(R.layout.fragment_control, container, false);
Bundle bundle = getArguments();
String ip=bundle.getString("ip");
Stirng port = bundle.getString("port");
Stirng uname = bundle.getString("uname");
Stirng password = bundle.getString("password");
答案 0 :(得分:3)
您正在设置构造函数而不是对象。使用以下代码
ControlFragment fragment = new ControlFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Bundle bundle = new Bundle();
bundle.putString("ip", o.get("ip"));
bundle.putString("port", o.get("port"));
bundle.putString("uname", o.get("uname"));
bundle.putString("password", o.get("password"));
Log.e("ip: ", "> " + o.get("ip"));
Log.e("port: ", "> " + o.get("port"));
Log.e("uname: ", "> " + o.get("uname"));
Log.e("password: ", "> " + o.get("password"));
fragment.setArguments(bundle);
transaction.replace(R.id.mainFrame, fragment );
transaction.replace(R.id.mainFrame,fragment);
这是改变。
答案 1 :(得分:0)
使用此行
Bundle bundle = getArguments();
在你的根视图出现之前
答案 2 :(得分:0)
在oncreate中创建oncreate视图之前获取数据。在设置data之前总是做一个空检查错误。希望这可以帮助你
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
String ip=bundle.getString("ip");
Stirng port = bundle.getString("port");
Stirng uname = bundle.getString("uname");
Stirng password = bundle.getString("password");
}
}
修改强>:
Amrish Kakadiya指出
transaction.replace(R.id.mainFrame,new ControlFragment());
这行代码正在创建问题,新的ControlFragment()创建了一个全新的片段实例,因此您在检索时将getArguments()视为null。