问题
I have an app with fragments. It works fine.
One of the fragments has a button, and when pressed I want to change the view.
public class BikeRecap extends Fragment {
public static Activity activity;
public static Context context;
/** Called when the activity is first created. */
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
activity = getActivity();
context = activity.getApplicationContext();
View view = inflater.inflate(R.layout.bike_recap, container, false);
ImageButton details = (ImageButton) item.findViewById(R.id.details);
details.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
OpenNewView();
}
});
return view;
}
OpenNewView() should change the view, so, the user is in the same tab, but the content is different
Is it possible?
回答1:
You can't have a fragment inside a fragment.
Try this code:
FragmentManager fragmentManager2 = getFragmentManager();
FragmentTransaction fragmentTransaction2 = fragmentManager2.beginTransaction();
DetailFragment fragment2 = new DetailFragment();
fragmentTransaction2.addToBackStack("abc");
fragmentTransaction2.hide(BikeRecap.this);
fragmentTransaction2.add(android.R.id.content, fragment2);
fragmentTransaction2.commit();
回答2:
I think you can, pretty easily, do what you are trying to do. If OpenNewView is implemented by the Activity, instead of by the fragment:
getActivity().openNewView(...)
... then the Activity can easily replace the current fragment with a new one, using the standard transaction mechanism.
G. Blake Meike Marakana
Programming Android 2ed is now in stores: http://bit.ly/programmingandroid
来源:https://stackoverflow.com/questions/14378705/change-fragment-view