我有一個Activity
的佈局由兩個Fragment
組成。其中一個片段佈局包含GridView
。GridView裏面的片段:getView永遠不會被調用
public class PicturesGallery extends FragmentActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_frames);
Fragment galleryFragment = fm.findFragmentById(R.id.gallery_fragment);
if (galleryFragment == null) {
fm.beginTransaction().add(R.id.gallery_fragment, new GalleryFragment()).commit();
}
...
當該片段稱爲它實例爲GridView
適配器,膨脹的GridView
和設置在適配器(這已被饋送有一個ArrayList
15項被顯示)。
public class GalleryFragment extends Fragment {
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Initialize the layout Adapter
PicturesGallery pga = (PicturesGallery) getActivity();
mAdapter = new ImageAdapter(pga.getApplication(), pga.mMemoryCache,
galleryDir);
mAdapter.mPictureNames = new ArrayList<String>(pictureNames);
// Inflate the layout and set the adapter
LayoutInflater inflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
GridView gridView = (GridView) inflater.inflate(R.layout.pictures_gallery_fragment, null);
gridView.setAdapter(mAdapter);
}
....
但在執行活動沒有任何反應(在logcat中,但是,GridView
顯示沒有任何錯誤)。在適配器類中,在getView()
內使用Log.d()
表示該方法從不調用。但是getCount()
會返回正確數量的項目。相關的代碼如下。
public class ImageAdapter extends BaseAdapter {
...
public ArrayList<String> mPictureNames = new ArrayList<String>();
public ImageAdapter(Context c, LruCache<String, Bitmap> mCache, File gallery) {
mMemoryCache = mCache;
mGalleryDir = gallery;
mInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("dupa", "getView");
ViewHolder vh;
View cell = convertView;
if (cell == null) {
vh = new ViewHolder();
cell = mInflater.inflate(R.layout.galleryitem, null);
// Populate the ViewHolder
vh.checkBox = (CheckBox) cell.findViewById(R.id.itemCheckBox);
...
cell.setTag(vh);
...
} else {
vh = (ViewHolder) cell.getTag();
}
// Update the cell View state
vh.checkBox.setTag(position);
...
return cell;
}
我沒有包含xml文件,因爲帖子很冗長。如果你認爲他們需要(或者你需要更多的代碼),請告訴我。任何幫助將不勝感激。 TIA。
謝謝。它工作正常。當視圖有適配器時,我對使用onCreateView vs onActivityCreated感到困惑。 – Vicent
完美,爲我的gridview工作 – Manny265