Tsunaze
Tsunaze

Reputation: 3254

listview and fragments

The thing is i'm creating a honeycomb app and i can't switch 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 .

Upvotes: 0

Views: 2334

Answers (2)

PJL
PJL

Reputation: 18794

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.

Upvotes: 1

500865
500865

Reputation: 7120

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.

Upvotes: 0

Related Questions