Reputation: 97
One of the activities in my app has three buttons in it and I used a switch to code them. I've used nearly identical code several other times in my app, but this particular one doesn't work. When I navigate to this screen and click any of the three buttons, nothing happens.
Here's the code that isn't working:
public void buttonOnClick(View view){
switch(view.getId()){
case R.id.generalPrefabButton:
Intent generalPrefabScreen = new Intent();
generalPrefabScreen.setClass(this, General_Prefab_Order.class);
startActivity(generalPrefabScreen);
break;
case R.id.conduitBendButton:
Intent conduitBendScreen = new Intent();
conduitBendScreen.setClass(this, Conduit_Bend_Order.class);
startActivity(conduitBendScreen);
break;
case R.id.safetyReportButton:
Intent safetyReportScreen = new Intent();
safetyReportScreen.setClass(this, Safety_Report.class);
startActivity(safetyReportScreen);
}
}
Upvotes: 1
Views: 65
Reputation: 1632
One way of achieving this is to make your class implement OnClickListener
and then add it to your buttons like this:
Example:
//make your class implement OnClickListener
public class MyClass implements OnClickListener{ ... //Create your buttons and set their onClickListener to "this"
Button generalPrefabButton = (Button) findViewById(R.id.buttonplay);
generalPrefabButton.setOnClickListener(this);
Button conduitBendButton = (Button) findViewById(R.id.buttonstop);
conduitBendButton.setOnClickListener(this); ...
//implement the onClick method here
public void onClick(View v) {
// Perform action on click
switch(v.getId()) {
case R.id.generalPrefabButton:
Intent generalPrefabScreen = new Intent();
generalPrefabScreen.setClass(this, General_Prefab_Order.class);
startActivity(generalPrefabScreen);
break;
case R.id.conduitBendButton:
Intent conduitBendScreen = new Intent();
conduitBendScreen.setClass(this, Conduit_Bend_Order.class);
startActivity(conduitBendScreen);
break;
case R.id.safetyReportButton:
Intent safetyReportScreen = new Intent();
safetyReportScreen.setClass(this, Safety_Report.class);
startActivity(safetyReportScreen);
break;
}
}
Upvotes: 1
Reputation: 450
Add this line to your Buttons in the layout .xml file: android:onClick="buttonOnClick"
<Button
android:id="@+id/button"
android:onClick="buttonOnClick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
Upvotes: 0
Reputation: 28228
Button button = new Button(R.id.generalPrefabButton);
button.setOnClickListener(this);
This sets the onClickListener activating the action in the onClick method.
Upvotes: 0