Home > database >  Social link don't added in Fragment
Social link don't added in Fragment

Time:05-12

I'm trying to add social media links in fragment in my app. When I staring adding img_vk, findViewById selected red color. In empty project ImageView working fine.

    public class Fragment5 extends Fragment {

    ImageView img_instagram,img_vk;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        img_vk = findViewById(R.id.img_vk);
        img_vk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gotoUrl("https://vk.com/1234");
            }
        });
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment5,container,false);
        return rootView;

    }
    private void gotoUrl(String s) {
        Uri uri = Uri.parse(s);
        startActivity(new Intent(Intent.ACTION_VIEW,uri));
    }
}

CodePudding user response:

So you should inflate the view of fragment first and then try to find your view in it.

So you should inflate the view of fragment first and then try to find your view in it.

public class Fragment5 extends Fragment {

    ImageView img_instagram,img_vk;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

      ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment5,container,false);
        img_vk = rootView.findViewById(R.id.img_vk);
        img_vk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gotoUrl("https://vk.com/1234");
            }
        });
       
        return rootView;

    }
    private void gotoUrl(String s) {
        Uri uri = Uri.parse(s);
        startActivity(new Intent(Intent.ACTION_VIEW,uri));
    }
}
  • Related