android - how to declare a widget from another layout?

不羁的心 提交于 2020-01-16 11:06:09

问题


I have a fragment layout that contains a class, but it needs to edit an imageview that is in another layout fragment. Example:

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);
      }
}

but if I do this, an error of type "attempt to invoke virtual method on a null object reference"

How could I manipulate this imageview that is in another fragment layout?


回答1:


The issue may be because you are paying null as a parent in inflater.

So instead of passing null in parent of

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

try passing a view in that like

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

But from your code I'm not sure that what's the value of layout variable inside add method.



来源:https://stackoverflow.com/questions/50195037/android-how-to-declare-a-widget-from-another-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!