skip to Main Content

I am trying to make a scientific calculator inside a fragment. Actually following a YT video and that guy is doing all that in his mainactivity not the fragment. I used this code in xml of my fragment:

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_scientific_calculator, container, false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    previousCalculation = view.findViewById(R.id.previousCalculationView);
    display = view.findViewById(R.id.displayEditText);

}

private void updateText(String strTOAdd) {
    display.setText(strTOAdd);
}

public void zeroBTNPush(View view) {
    updateText("0");
}

All I know is that to use findViewById in a fragment, I have to create a onViewCreated void. So after doing all this I should get the updateText function in fragment.java>design>attributes>onClick but I get nothing there
enter image description here
I’m new to this. Please help

3

Answers


  1. You can just set OnClickListener in your fragment code like this

    someBtn.setOnClickListener(new OnClickListener(){
        // call the method you want to be excecuted when the buttun is being pressed
    })
    

    also you can specify it in the design, but for example I would prefer to work with the XML code directly – it’s much more understantable for me

    Login or Signup to reply.
  2. To use findViewById I think all you need is a View object, which is returned by onCreateView, so you could just do:

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_scientific_calculator, container, false);
        Button btn = view.findViewById(R.id.yourButtonId); 
        btn.setOnClickListener((View v) -> {
            // do something here
        });
    }
    
    Login or Signup to reply.
  3. You can do this in onViewCreated with the view that is passed in by getting the button and setting a click listener on it like this:

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    
        //...
    
        Button myButton = view.findViewById(R.id.myButton);
        myButton.setOnClickListener((View v) -> {
            // do button stuff
        });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search