社交 link 未添加到 Fragment 中

Social link don't added in Fragment

我正在尝试在我的应用中以片段形式添加社交媒体链接。当我开始添加 img_vk 时,findViewById 选择了红色。在空项目 ImageView 中工作正常。

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

所以你应该先膨胀片段的视图,然后尝试在其中找到你的视图。

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