我是Android的新手,我不太明白为什么动态添加的Fragment
内容(例如在单击按钮后添加的一些图像)在滚动一定数量的Fragment
之后消失,然后再次出现。
这里有一个非常简单的Activity
和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>
逻辑很简单。在每个片段
上,我可以点击一个按钮
,结果会出现一张图片。
这也起作用。但是...
当我在第一个片段中显示图像,然后滚动到第三个片段并再次回到第一个片段时,图像就消失了。
我应该怎么做来防止这种情况?我是否应该以某种方式保存可见性状态?