0

I created a method that I was going to link to a Button on my Fragment.

For some reason when I put the method in the Fragment and go to the layout file for the fragment, the button's on click property doesn't seem to recognize the method. When I put the identical method within the main Activity it seems to recognize the method just fine, but I want to have this method exist within my Fragment.

Does anyone know how I can fix this while still having the method exist in my Fragment?

public void onClicFragment(View v)
{

}
earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63
Enryu
  • 1,406
  • 1
  • 14
  • 26
  • you need that in activity. or get the button's reference in frragment and have a click listener. have a look @ https://stackoverflow.com/questions/6091194/how-to-handle-button-clicks-using-the-xml-onclick-within-fragments – Raghunandan Jun 08 '17 at 06:24
  • could you add the code of your fragment ? And the layout you use ? – Timo Jun 08 '17 at 06:32
  • It's a very simple fragment, but here are screenshots of the fragment and the xml layout file. https://puu.sh/we7Zv/71638ab7d3.png https://puu.sh/we80H/a768eece94.png – Enryu Jun 08 '17 at 06:35

1 Answers1

1

If your Button is in your Fragment, you just simply have to add an OnClickListener to it (in onCreateView() for example):

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.some_layout, parent, false);
    Button button = (Button) view.findViewById(R.id.some_button);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // ...
        }
    });

    return view;
}

Otherwise, you could define the onClick method in your Activity and call the appropriate method of your Fragment from there:

public class MainActivity extends AppCompatActivity {

    // ...

    public void onClickFragment(View v) {
        SomeFragment f = (SomeFragment) getFragmentManager().findFragmentByTag("SOME_TAG");
        if (f != null) {
            f.someMethod();
        }
    }
}
earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63
  • Alright I created a listener in the fragment, but getting the references was a little awkward. Is this typically where you would get the references for a fragment or should I be getting the references somewhere after onCreateView. https://puu.sh/we8sn/2eeb980e79.png – Enryu Jun 08 '17 at 06:49