The thing is i'm creating a honeycomb app and i can't switch开发者_如何学JAVA between fragments . Here's my main code :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView)findViewById(R.id.list);
A = new FragmentA();
B = new FragmentB();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(adapter);
list.setOnItemClickListener(mylistener);
}
public void changeFragment(Fragment f){
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment, f);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
public OnItemClickListener mylistener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
switch(position){
case 0 : changeFragment(A);
break;
case 1 : changeFragment(B);
break;
}
}
};
I know before i put a "replace" i have to remove but how can i remove the one i'm already in ? What is telling me in the log : The specified child already has a parent. You must call removeView() on the child's parent first .
Have a look at the API demos FragmentLayout sample as it does something similar to what you want I believe. There's nothing wrong with calling replace
to load the first fragment as that sample demonstrates.
Firstly add some protection so when when you click on the same list entry you don't reload the same fragment.
Secondly be careful when maintaining references to fragments, see link. You may want to recreate the fragments each time or use remove
and add
instead of replace
.
The problem is not with removing the fragment. The replace
method removes the existing one.
I guess the problem is accessing the fragment inside the listener. Try creating a new fragment inside the listener itself. Please post the complete code.
精彩评论