0

我目前正在尝试在片段中使用 ABS(ActionBarSherlock) 制作 GridView。但我遇到了一些问题,得到 NPE(NullPointerException)。这是我的片段代码:

public class Fragment2 extends SherlockFragment {

GridView gridView;
ImageAdapter imgAdapter;
private Context context;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment2, container, false);
    gridView = (GridView) rootView.findViewById(R.id.gridview);
    context = getSherlockActivity();
    gridView.setAdapter(new ImageAdapter(context));

    return rootView;
}   

还有我的 ImageAdapterClass:

public class ImageAdapter extends BaseAdapter {

// references to our images
private Integer[] mThumbIds = {
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_0, R.drawable.sample_1,
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_0, R.drawable.sample_1,
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7
};

private static Context mContext;

public ImageAdapter(Context c) {
    mContext = c;
}

public int getCount() {
    return mThumbIds.length;
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}

// create a new ImageView for each item referenced by the Adapter
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(85, 85));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }

    imageView.setImageResource(mThumbIds[position]);
    return imageView;
}

}

最后是我的 LogCat:

10-25 01:06:32.239: E/AndroidRuntime(12344):    at com.AlexPrograms.NavDrawerSherlock.Fragment2.onCreateView(Fragment2.java:24)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at android.os.Handler.handleCallback(Handler.java:587)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at android.os.Handler.dispatchMessage(Handler.java:92)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at android.os.Looper.loop(Looper.java:130)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at android.app.ActivityThread.main(ActivityThread.java:3687)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at java.lang.reflect.Method.invokeNative(Native Method)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at java.lang.reflect.Method.invoke(Method.java:507)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
10-25 01:06:32.239: E/AndroidRuntime(12344):    at dalvik.system.NativeStart.main(Native Method)

如果你能找到问题所在,我会尽力而为。提前致谢

4

2 回答 2

0

嗯,第一件事。该片段设计不当。;)

这一行:

context = getSherlockActivity(); 

可能会崩溃。

将上下文传递给 Fragment 的正确(首选和标准)方式应该是这样的:

public class YourFragment extends SherlockFragment  {
    private static Context sContext;
    public static YourFragment newInstance(Context context) {
        if (context != null) {
            sContext = context.getApplicationContext();
        } else {
            sContext = YourAppInstance.getInstance().getApplicationContext();
        }
        return new YourFragment();
    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }
    private void init() {
       // Add anything else you need (and can) init.
        if (sContext == null) {
            sContext = mApp.getApplicationContext();
        }

    }
@Override
protected void onResume() {
    super.onResume();
            init(); // in case of a resume overnight where stuff may be null
    }
    // NOW YOUR STUFF
    private GridView mGridView;
    private ImageAdapter mImgAdapter;

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
         final Bundle savedInstanceState) {
         final View rootView = inflater.inflate(R.layout.fragment2, container, false);
         mGridView = (GridView) rootView.findViewById(R.id.gridview);
         if ( mGridView != null && sContext != null ) {
             mImgAdapter = new ImageAdapter(sContext);
             mGridView.setAdapter(mImgAdapter);
         }

         return rootView;
    }  
}

这看起来更像 Android ......</p>

现在,在片段中使用 getSherlockActivity() 之前,建议先做一个

if (getSherlockActivity() != null && !getSherlockActivity().isFinishing() ) {
   //Safe to use getSherlockActivity here
}

最后但并非最不重要的……</p>

你的 ImageAdapter…</p>

public Object getItem(int position) {
    return null;
}

正在返回 null,因此网格中包含所有 null 项……

也许你的意思是……</p>

  public Object getItem(int position) {
        return mThumbIds[position]
  }

我的意思是,你的图像适配器到底是什么适配器?参考图像?这有点奇怪,因为它是硬编码的,但是你必须返回一些东西,记住 Grid 会向它的适配器询问视图,而适配器需要找到数据来创建那个视图。

于 2013-10-25T00:11:49.867 回答
0

我刚刚克服了 ABS 以及何时将 ActionBar Compat 与 de Support Lib 兼容。

这是我的片段类。

public class FragmentCategories extends Fragment {

private GridView vGrid;
private Context vContenx;

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

    vContenx = getActivity();

    vGrid = (GridView) primalView.findViewById(R.id.gridview);
    vGrid.setAdapter(new GridAdapter(vContenx));


    return primalView;
}

以及我的 GridView 适配器的 getView

@Override
public View getView(int pos, View gridView, ViewGroup fatherGroup) {

    catNames = mContext.getResources().getStringArray(R.array.value_Cats);

    ImageView imageView;
    TextView  textView;
    if (gridView == null) { 
        gridView = mlayoutPrinter.inflate(R.layout.grid_items, null);
        imageView = (ImageView) gridView.findViewById(R.id.img);
        imageView.getLayoutParams().height = 120;

        textView =  (TextView) gridView.findViewById(R.id.TextItem);
        textView.setText(catNames[pos]);
        gridView.setTag(imageView);
        textView.setTag(textView);
    } else {
        imageView = (ImageView)gridView.getTag();
    }


    imageView.setImageResource(mThumbIds[pos]);


    return gridView;
}

以及包含 GridView 的片段的 XML

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/FrameLayout1"
    android:layout_width="match_parent"
    android:background="@color/BandHookGrey"
    android:layout_height="match_parent"
    tools:context=".FragmentCategories" >

<GridView
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:numColumns="2"
    android:padding="5dp"
    android:horizontalSpacing="7dp"
    android:verticalSpacing="7dp"
    android:background="@color/BandHookGrey"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

最后是填充网格的布局的 XML。

<LinearLayout 
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/GridItemImage"
      android:layout_width="wrap_content"
      android:orientation="vertical"
      android:background="#FFF"
      android:layout_height="wrap_content">

<ImageView 
    android:id="@+id/img"
    android:layout_height="120dp"
    android:layout_margin="5dp"
    android:layout_width="match_parent"
    android:contentDescription="@string/content"/>

<TextView 
    android:id="@+id/TextItem"
    android:layout_width="match_parent"
    android:gravity="center"
    android:background="@android:color/transparent"
    android:layout_height="wrap_content"
    android:textColor="@color/gridText"
    android:textSize="16sp"
    android:paddingBottom="2dp"
    android:singleLine="true"/>

于 2013-11-03T00:57:12.167 回答