Search code examples
javaandroidbottomnavigationview

Moving from a fragment to a new activity


I have BottomNavigation and am now in the first snippet. In the first fragment there are two buttons, I need to be thrown to a new activity by pressing these buttons. I do not understand how to implement it correctly. I get an error.

Code,eror

public class Fragment1 extends Fragment {



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

        ViewGroup rootView=null;


        rootView=(ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
        return rootView;

        Button button=(Button) rootView.findViewById(R.id.btn1);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), One.class);
                startActivity(intent);
            }


        });
    }
}

Solution

  • Place the return rootView at the end of the code block:

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup rootView = inflater.inflate(R.layout.fragment1, container, false);
    
        Button button=(Button) rootView.findViewById(R.id.btn1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), One.class);
                startActivity(intent);
            }
        });
    
        return rootView;
    }