问题
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