Edward Muldrew Edward Muldrew - 4 years ago 145
Java Question

Android Studio | How to use On Click to switch between a fragment and activity

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download