1

在 Fragment 类中为 ImageView 添加 setOnClickListener 时遇到问题。由于 NullPointerException,当我单击 ImageView 时发生错误。

下面是我的代码:

public final class TestFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ImageView image = new ImageView(getActivity());
    image.setTag(mContent);
    image.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        HomeActivity h = new HomeActivity();
        String url = h.getEventUrl();

        Intent childClass = new Intent(getActivity(), HomeEventDetailActivity.class);

        childClass.putExtra("eventUrl",url);
        TabGroupActivity parentActivity = (TabGroupActivity)h.getParent();
        parentActivity.startChildActivity("Child_Main1", childClass);
    }
});
    imageManager.displayImage(mContent, image, R.drawable.icon);
    image.setScaleType(ScaleType.FIT_XY);

    LinearLayout layout = new LinearLayout(getActivity());
    layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    layout.setGravity(Gravity.CENTER);
    layout.addView(image);

    return layout;
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString(KEY_CONTENT, mContent);

    setUserVisibleHint(true);
}
}

请帮忙!!!!

4

1 回答 1

1

我认为问题出现在这一行:

ImageView image = new ImageView(getActivity());

不要将片段宿主活动作为参数(通过 getActivity())传递给此构造函数,而是尝试传递在 onCreateView 方法末尾返回的布局变量。

ImageView image = new ImageView(layout);

代码看起来像这样:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
layout.setGravity(Gravity.CENTER);

ImageView image = new ImageView(layout);
image.setTag(mContent);
image.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
    HomeActivity h = new HomeActivity();
    String url = h.getEventUrl();

    Intent childClass = new Intent(getActivity(), HomeEventDetailActivity.class);

    childClass.putExtra("eventUrl",url);
    TabGroupActivity parentActivity = (TabGroupActivity)h.getParent();
    parentActivity.startChildActivity("Child_Main1", childClass);
}
});
imageManager.displayImage(mContent, image, R.drawable.icon);
image.setScaleType(ScaleType.FIT_XY);
layout.addView(image);
return layout;

}

于 2013-08-27T17:28:41.933 回答