首页 > 解决方案 > android - 如何从另一个布局声明一个小部件?

问题描述

我有一个包含类的片段布局,但它需要编辑另一个布局片段中的图像视图。例子:

public class LayoutFragment extends Fragment {
private ImageView imageView;

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

    imageView = view.findViewById(R.id.imageView); // this imageview is not fragment_layout, he is in fragment_layout2

    addChild();

    return view;
}

private void addChild() {
    LayoutInflater inflates = LayoutInflater.from(getContext());
    int id = R.layout.dynamic_layout_budget;
    LinearLayout relativeLayout = (LinearLayout) inflates.inflate(id, null, false);

    imageView.setImageBitmap(bitmap);

    layout.addView(relativeLayout);
      }
}

但如果我这样做,则会出现“尝试在空对象引用上调用虚拟方法”类型的错误

我怎样才能操纵另一个片段布局中的这个图像视图?

标签: javaandroidandroid-studio

解决方案


问题可能是因为您在 inflater 中作为父母支付 null。

因此,不要在父级中传递 null

LinearLayout relativeLayout = (LinearLayout) inflates.inflate(id, null, false);

尝试传递一个类似的视图

LinearLayout relativeLayout = (LinearLayout) inflates.inflate(id, layout, false);

但是从您的代码中,我不确定layoutadd 方法中变量的值是什么。


推荐阅读