-1

Hi I am trying to find out how to replace a fragment by clicking on a button within a fragment.

I tried looking into this article but it did not work for me.

 View view = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getView();
    btnGoToSignUp = view.findViewById(R.id.btnGoToSignUp);

I tried this but it comes up with the error

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.v4.app.Fragment.getView()' on a null object reference

Anmol
  • 8,110
  • 9
  • 38
  • 63
sixcookies
  • 357
  • 1
  • 7
  • 22
  • `getSupportFragmentManager().findFragmentById(R.id.fragment_container)=null` it means your fragment doesn't even exist i.e fragment is destroyed when you are trying to access the view of the fragment – Anmol Jan 06 '19 at 08:09

1 Answers1

2

You could just do this:

Interface:

public interface BtnClickable {
    void myClickMethod(View v);
}

Fragment:

    public class SomeFragment  {
BtnClickable btnClickable;
    //...onCreateView, etc.

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_add_note, container, false);
    Button btnGoToSignUp = root.findViewById(R.id.btnGoToSignUp);

    btnGoToSignUp.setOnClickListener(new OnClickListener() {
        public void onClick(View v)
        {
    btnClickable.myClickMethod(v);
        } 
    });



    }
public static void setClickListener(BtnClickable listener){
btnClickable=listener;
}

Activity:

    class MyActivity implements BtnClickable {

        //...onCreate etc instantiating your fragments
               public void onCreate(Bundle savedInstanceState)
    {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.filters); 
        SomeFragment.setClickListener(this); 

    }

        public void myClickMethod(View v) {
       // you can listen here for btn clicked 

        }



}
Mohammed Mahmoud
  • 1,138
  • 10
  • 14
  • Hi, I think you're on the right path but I have this error java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.android.memo.FragmentCommunicator.changeFragment(android.view.View, java.lang.String)' on a null object reference – sixcookies Jan 06 '19 at 09:10