Skip to content

Instantly share code, notes, and snippets.

@amrro
Last active March 7, 2016 15:33
Show Gist options
  • Save amrro/346b0764707f32bd68db to your computer and use it in GitHub Desktop.
Save amrro/346b0764707f32bd68db to your computer and use it in GitHub Desktop.
Two switches within android activity, and button to click to get the final result.
package com.weathers.amro.tests;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
final int VALUE1 = 50; // value for first switch.
final int VALUE2 = 20; // value for second switch.
private int total; // total value to display.
private Switch switch1;
private Switch switch2;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switch1 = (Switch) findViewById(R.id.switch1);
switch2 = (Switch) findViewById(R.id.switch2);
button = (Button) findViewById(R.id.button);
total = 0; //initialize variable.
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
total = calculateTotal();
/*
* add your code, comparison, or any editting here.
*/
Toast.makeText(
getApplicationContext(),
"Total: " + total,
Toast.LENGTH_SHORT)
.show();
}
});
}
/**
* helper function to check all switches
* @return final value.
*/
private int calculateTotal()
{
int cal = 0;
// was first switch ON?
if (switch1.isChecked())
cal += VALUE1;
// second switch?
if (switch2.isChecked())
cal += VALUE2;
return cal;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment