How to use Picasso in onCreateView?

Adam Szymański :

I have problem with Picasso code. In my fragment_home (fragment of navigation bar) is ImageView where I want to put image from "image.com" URL addres. Picasso code look like that

Picasso.get().load("image.com")
                .resize(300,200)
                .centerInside()
                .into(photo);

I cant write that into my HomeFragmentActivity where code suppose to be because findViewById isn't "working".

HomeFragmentActivity > Place where code have to be

public class HomeFragment extends Fragment {
    private ImageView photo;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home /*in this layout is ImageView where Picasso is inserting image from URL addres*/) , container, false);
    }
}

When code is somewhere else (for example in MainActivity in onCreate method) app will crash. Please help. Thanks.

Write below you'r suggests, maybe Picasso code don't must be in HomeFragmentActivity ?

Kasım Özdemir :

You can declare it like this :

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_home, container, false);
    photo = view.findViewById(R.id.photo);
    Picasso.with(context).load("url")
            .resize(300,200)
            .centerInside()
            .into(photo);
    return view;
}

or

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    photo = view.findViewById(R.id.photo);
    Picasso.with(context).load("url")
            .resize(300,200)
            .centerInside()
            .into(photo);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=403918&siteId=1