I have an Activity and 3 fragments. At the bottom of the main activity I have 3 buttons for switching the active fragment. Each fragment contains a ListView, do you think is a good way of development? I've developed the first Fragment downloading json from server, parsing and adding the element to the ListView, but when I press the button to switch to the Fragment2 the first one stays.
This is the main activity, the Fragment with the listView is using a custom adapter within some TextView and one ImageView. If I remove the listView, the fragments change without troubles.
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
public class Home extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_home);
}
public void selectFrag(View view) {
Fragment fr;
int stringTitleID = R.string.title_fragment1;
if(view == findViewById(R.id.imgBtn3))
{
fr = new FragmentThree();
stringTitleID = R.string.title_fragment3;
}
else if(view == findViewById(R.id.imgBtn2))
{
fr = new FragmentTwo();
stringTitleID = R.string.title_fragment2;
}
else
{
fr = new FragmentOne();
stringTitleID = R.string.title_fragment1;
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
// I change the title in the top_bar
TextView textViewActivityTitle = (TextView) findViewById(R.id.textViewActivityTitle);
textViewActivityTitle.setText(getResources().getString(stringTitleID).toString());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
/*
* This functions clears the app cache. The json responses are stored in che cacheDir or cacheExternalDir.
* I clean them when the app is started. I only use the cache between the Fragments
*/
}
Is the fragments solution a good one? Why the fragment with the listview stays? Should I use a ListFragment?
Thanks a lot.