默认情况下,listview片段将在我的活动中显示1
这是我的活动:
public class SecondActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
FragmentManager manager = getFragmentManager();
FragmentTransaction tran = manager.beginTransaction();
ListViewFragment fr = new ListViewFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("Object", getIntent().getParcelableExtra("ObjectFromCategory"));
fr.setArguments(bundle);
tran.addToBackStack(null);
tran.replace(R.id.places_fragment_cointainer, fr, "ListView");
tran.commit();
//handleFragmentCycle();
}
然后在ListviewFragment我得到参数:
public class ListViewFragment extends Fragment implements OnClickListener {
private TextView mTxtMapView;
private Category mObject;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = inflater.inflate(R.layout.fragment_places_listview, container,false);
mTxtMapView = (TextView)v.findViewById(R.id.txt_mapview);
mObject = getArguments().getParcelable("Object");
Toast.makeText(getActivity(), mObject.getText(), Toast.LENGTH_LONG).show();
mTxtMapView.setOnClickListener(this);
return v;
}
这是我的MapViewFragment:
public class MapViewFragment extends Fragment implements OnClickListener {
TextView txtListView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = inflater.inflate(R.layout.fragment_places_mapview, container, false);
FragmentManager fm = getChildFragmentManager();
MapFragment supportMapFragment = MapFragment.newInstance();
fm.beginTransaction().replace(R.id.mapwhere, supportMapFragment).commit();
txtListView = (TextView) v.findViewById(R.id.txt_listview);
txtListView.setOnClickListener(this);
return v;
}
第一次创建ListViewFragment时,我可以成功获取参数,但是当我更改为MapViewFragment然后又更改回ListViewFragment时,我将为null。我想出了一个解决方案,我应该在bundle中传递一个int值,以检测是否从Activity或MapViewFragment创建了ListViewFragment。但是我不认为这是一个很好的解决方案,因为我仍然想获得Category Objecct,所以我想听听是否有人对此案例有更好的解决方案。谢谢!
最佳答案
您可以在“活动”中使用gjson将对象存储到SharePreference
。
然后在Fragment中,从SharePreference
检索对象。
之后,您将永远不会在null
中获得Fragment
对象
===
这是从SharePreference
保存和检索对象的方法
创造
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);//Creating shared preference
用于保存对象
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject); // myObject - instance of MyObject
prefsEditor.putString("Object", json);
prefsEditor.commit();
用于检索对象
Gson gson = new Gson();
String json = mPrefs.getString("Object", "");
MyObject obj = gson.fromJson(json, MyObject.class);