gpt4 book ai didi

android - 空指针异常 : SetOnClickListener in Fragment Class

转载 作者:行者123 更新时间:2023-11-30 04:07:03 24 4
gpt4 key购买 nike

当我在 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);
}
}

请帮忙!!!!

最佳答案

我认为问题出在这一行:

ImageView image = new ImageView(getActivity());

与其将 fragment 宿主 Activity 作为参数(通过 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;

关于android - 空指针异常 : SetOnClickListener in Fragment Class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11429904/

24 4 0
文章推荐: android - 在Android SDK 版本中,20 为什么开发组删除了android 项目创建窗口中的 "create project for existing source"?
文章推荐: android - 在为 MDPI 和 HDPI ANdroid 设计 UI 界面时,我如何解决高度问题?
文章推荐: android - 在 x,y 图像中设置图像
文章推荐: android - 将 ArrayList 存储为 JSON SharedPreference 或 SQLite 数据库表?