I am new in Android and I don't really understand why a Fragment
's content which was added dynamically (for example some image which was added after a button click) is disappearing after scrolling some count of Fragment
s and then come back.
There is really simple code Activity
and Fragment
:
public class MyActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
final CustomAdapter adapter = new CustomAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
}
class CustomFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getView().findViewById(R.id.clickMeButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getView().findViewById(R.id.image).setVisibility(View.VISIBLE);
}
});
}
}
class CustomAdapter extends FragmentStatePagerAdapter {
private List<CustomFragment> fragments = Arrays.asList(
new CustomFragment(),
new CustomFragment(),
new CustomFragment()
);
public CustomAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
return fragments.get(i);
}
@Override
public int getCount() {
return fragments.size();
}
}
}
and appropriate xmls:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.support.v4.view.ViewPager
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/viewPager" />
</LinearLayout>
fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/clickMeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click me"/>
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:visibility="gone"/>
</LinearLayout>
Logic is simple. On each Fragment
I can click on a Button
and as result an image appears.
And it works. But ...
When I show image on the first fragment, then scroll to the third one and come back to first one again image is gone.
What should I do to prevent this ? Should I somehow save state of visibility?