Reputation: 41
Would anyone be kind enough to help me? I am making an android app that uses toggle buttons to collect user answers in the form of yes and no (on and off respectively). I have set up the following branch in the first buttons on click listener method:-
If the toggle is clicked, Use an already declared and initialised local variable to store a number (eg, 1) Else Use the already declared and initialised variable to store a different number (eg, 2)
Well. I realise I cannot use local variables in another method, however I want to collect the variables from all the toggle buttons so that I can calculate a user score somewhere else in the program. How would I do this?
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
public class NewActivity1 extends Activity{
public static int exportNumber1 = 0;
public static int exportNumber2 = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_activity1);
final TextView textView = (TextView) findViewById(R.id.textView11);
textView.setText("" + exportNumber1);
final ToggleButton atb1 = (ToggleButton) findViewById(R.id.toggleButton1);
atb1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
int x = 0;
if (atb1.isChecked())
{
x = 1;
}
else
{
x = 2;
}
exportNumber1 = x;
}
});}}
Upvotes: 3
Views: 4485
Reputation: 2943
You should declare those variables globally (after your Activity/class declaration.)
This way you will be able to access the from any method you desire within that activity.
ex:
public class MyActivity extends Activity {
public int toggle1, toggle2, toggle3....
//or String or whaterever, you can use these variables to store the values the user selects from within your OnClick listener
Upvotes: 2