Reputation: 31
I'm programming an assignment, and I've got the core functionality operating but I'm quite confused with this. I have 3 buttons on this Activity/Fragment, and each one sends an Intent to a new Activity with a different integer to set the speed of the main game.
Button 1 sets the speed 10, button 2 sets the speed 30, and button 3 sets the speed 50. However, whichever one I click, it starts the Activity with speed 50 first, then when that Activity is finished, it is started with speed 30, and then again after with speed 10. It is essentially cycling and starting all possible Activities, but I only want the selected one starting.
This is the code, as far as I can understand it's somewhere in here.
public class LevelsFragment extends Fragment implements OnClickListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_levels, container, false);
Button b1 = (Button)rootView.findViewById(R.id.button1);
Button b2 = (Button)rootView.findViewById(R.id.button2);
Button b3 = (Button)rootView.findViewById(R.id.button3);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
return rootView;
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button1:
Intent i1 = new Intent(getActivity(), GameActivity.class);
i1.putExtra("s", 10);
startActivity(i1);
case R.id.button2:
Intent i2 = new Intent(getActivity(), GameActivity.class);
i2.putExtra("s", 30);
startActivity(i2);
case R.id.button3:
Intent i3 = new Intent(getActivity(), GameActivity.class);
i3.putExtra("s", 50);
startActivity(i3);
}
}
}
Upvotes: 0
Views: 105
Reputation: 2603
This one's a classic, you forgot to put a break;
between the different cases.
Upvotes: 2
Reputation: 78609
You forgot to put a break
in your switch statements.
switch (v.getId())
{
case R.id.button1:
Intent i1 = new Intent(getActivity(), GameActivity.class);
i1.putExtra("s", 10);
startActivity(i1);
break;
case R.id.button2:
Intent i2 = new Intent(getActivity(), GameActivity.class);
i2.putExtra("s", 30);
startActivity(i2);
break;
case R.id.button3:
Intent i3 = new Intent(getActivity(), GameActivity.class);
i3.putExtra("s", 50);
startActivity(i3);
break;
}
Upvotes: 2