1

I am trying to use a button to switch between the fragment I am working on to a new activity. I am using the On Click listener to try switch. As well as using start activity. I think I may have to use fragment manager but I am unsure of how to use this.

This is the code I have.

addPlayers.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        startActivity(new Intent(TeamManagementFragment.this,AddPlayer.class));
    }
});

The error message I have is "Cannot resolve constructor"

Your help would be greatly appreciated :). Many thanks, Edward.

petey
  • 16,914
  • 6
  • 65
  • 97
Edward Muldrew
  • 77
  • 1
  • 13

4 Answers4

1

I suppose that AddPlayer is an Activity. So you can use getActivity() instead of TeamManagementFragment.this

Valentino
  • 2,125
  • 1
  • 19
  • 26
0

Assuming AddPlayer is your other activity you want to start, use the context from the View v argument as your first argument to the new Intent creation instead of using the current TeamManagementFragment instance since they are not a valid context.

addPlayers.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        startActivity(new Intent(v.getContext(), AddPlayer.class));
    }
});

See the docs page for Context to see which classes inherit from it : https://developer.android.com/reference/android/content/Context.html

petey
  • 16,914
  • 6
  • 65
  • 97
  • Petey Thank you very much! This worked for me! Just out of interest, I assume the v.getContext() means it gets the view that it is on? – Edward Muldrew Feb 06 '17 at 19:07
  • Yea! the `v` argument will actually be what view was clicked, this is because you can apply the same OnClickListener to many views. In the above example `v` will be equal to `addPlayers`. – petey Feb 06 '17 at 19:08
  • I have done! I am trying to switch back between the new Add Player Activity and Team Management fragment. startActivity(Intent(v.getContext(),TeamManagementFragment.class)); My error says it can't resolve method. – Edward Muldrew Feb 06 '17 at 19:33
  • Just return the activity that you were on before, you may want to look at this answer from another question : http://stackoverflow.com/a/10407371/794088 – petey Feb 06 '17 at 20:25
0

well I guess you didn't get the concept of activities and fragments. a fragment is basically a view which is hosted by an activity, and it's alive as long as the container activity lives. you can not use an intent to switch between these two.

mamzi
  • 495
  • 5
  • 11
0

Try this as you are currently in fragment:

addPlayers.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { 
    getActivity().startActivity(new Intent(getActivity(),AddPlayer.class)); 
    } 
});
ChaitanyaAtkuri
  • 1,672
  • 11
  • 15