2013-10-28 104 views
1

將指針適配器分配給片段中的視圖時爲空指針。將指針適配器分配給片段中的GridView時的空指針

我有一個包含片段的活動。我想用GridView填充Fragment。

public class MyBaseAdapter extends BaseAdapter { 

     private Context mContext; 
     private List<ResolveInfo> mAppList; 

     MyBaseAdapter(Context c, List<ResolveInfo> l) { 
      mContext = c; 
      mAppList = l; 
     } 
     public int getCount() { 
      return mAppList.size(); 
     } 
     public Object getItem(int position) { 
      return mAppList.get(position); 
     } 
     public long getItemId(int position) { 
      return position; 
     } 

     public View getView(int position, View convertView, ViewGroup parent) { 
      ImageView imageView; 
      if (convertView == null) { 
       // if it's not recycled, initialize some attributes 
       imageView = new ImageView(mContext); 
       imageView.setLayoutParams(new GridView.LayoutParams(200, 200)); 
       imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
       imageView.setPadding(8, 8, 8, 8); 
      } else { 
       imageView = (ImageView) convertView; 
      } 

      ResolveInfo resolveInfo = mAppList.get(position); 
      imageView.setImageDrawable(resolveInfo 
        .loadIcon(mPackageManager)); 
      return imageView; 
     } 
    } 

我已經實現了片段 - - 對於我創建了一個自定義適配器

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.grid_of_app, container, false); 

     HashMap<String, String> pkClsPair = new HashMap<String, String>(); 
     pkClsPair.put("com.android.contacts", "com.android.contacts.activities.PeopleActivity"); 
     pkClsPair.put("com.android.gallery", "com.android.camera.GalleryPicker"); 

     mPackageManager = getActivity().getPackageManager(); 
     List<ResolveInfo> intentList = null, intentList_temp = null; 

     Intent intent = new Intent(Intent.ACTION_MAIN, null); 
     intent.addCategory(Intent.CATEGORY_LAUNCHER); 
     for (Map.Entry<String, String> entry : pkClsPair.entrySet()) { 
      intent.setClassName(entry.getKey(), entry.getValue()); 
      if (intentList == null) 
       intentList = getActivity().getPackageManager().queryIntentActivities(intent, 0); 
      else { 
       intentList_temp = (getActivity().getPackageManager().queryIntentActivities(intent, 0)); 
       intentList.addAll(intentList_temp); 
      } 
     } 

     mBaseAdapter = new MyBaseAdapter(getActivity(), intentList); 
     GridView mGridview = (GridView) getActivity().findViewById(R.id.gridView); 
     mGridview.setAdapter(mBaseAdapter); 

     mGridview.setOnItemClickListener(mOnItemClickListener); 

     return rootView; 
    } 

不過,我似乎得到一個空指針異常而分配適配器 - mBaseAdapter - 到GridView 。據我所知它應該工作,因爲我正在提供一個適當的上下文適配器(我調試時也檢查它,值不爲空)。

在此先感謝。

回答

2
GridView mGridview = (GridView) getActivity().findViewById(R.id.gridView); 
在上面一行變化

getActivity()rootView

+0

看來工作。你能解釋爲什麼rootView?爲什麼只有findViewByID()會給出一個靜態引用錯誤? –