我試圖創建一個圖片庫,使用this tutorial作爲指南,進行了一些調整。setRetainInstance(true),但UI不出現
因此,這裏是我的代碼片段部分:
public static class PlaceholderFragment extends Fragment {
private static final String TAG = "com.example.imageencryptor.RetainedFragment";
LruCache<String, Bitmap> cache;
public PlaceholderFragment() {
initCache();
}
public void initCache() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
final int cacheSize = maxMemory/8;
cache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return ImageLoader.getSizeInBytes(bitmap)/1024;
}
};
}
public static PlaceholderFragment findOrCreateRetainFragment(
FragmentManager fm) {
PlaceholderFragment fragment = (PlaceholderFragment) fm
.findFragmentByTag(TAG);
if (fragment == null) {
fragment = new PlaceholderFragment();
fm.beginTransaction().add(fragment, TAG).commit();
}
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
GridView imageGrid = (GridView) rootView
.findViewById(R.id.gridview);
ImageLoader loader = new ImageLoader(getActivity(), cache);
imageGrid.setAdapter(new ImageAdapter(getActivity(), loader));
return rootView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
}
我活動的onCreate方法是這樣的:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PlaceholderFragment.findOrCreateRetainFragment(getSupportFragmentManager());
}
不過,我結束了在啓動一個空白的UI。沒有網格視圖。這是爲什麼?
在另一方面,如果我的onCreate改變這個它會工作:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PlaceholderFragment pFragment = PlaceholderFragment
.findOrCreateRetainFragment(getSupportFragmentManager());
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, pFragment,PlaceholderFragment.TAG).commit();
}
}
但不喜歡它,一遍又一遍,只要添加多個相同的片段用相同的標籤,給FragmentManager屏幕方向改變?
嗨,你測試了我的答案嗎?你找到解決方案還是需要更多解釋? – Fllo