Java (android) How to use a variable of a method in another method… here is a solution to the problem.
Java (android) How to use a variable of a method in another method
I’m retrieving the value of a TextView like this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculation);
TextView heading = (TextView) findViewById(R.id.paper_name);
......
}
I have another method in the same class
@Override
public void onClick(View v) {
int BLACK_AND_WHITE_MULTIUPLIER = 4200;
int COLOR_MULTIUPLIER = 6400;
switch (v.getId()) {
case R.id.btCalculate:
int multiplier = rbColor.isChecked() ? COLOR_MULTIUPLIER : BLACK_AND_WHITE_MULTIUPLIER;
int column = Integer.parseInt((String) spColumn.getSelectedItem());
int inch = Integer.parseInt((String) spInch.getSelectedItem());
tvAmount.setText((multiplier * column * inch) + "");
break;
}
}
I want to set the values of COLOR_MULTIUPLIER
and BLACK_AND_WHITE_MULTIUPLIER
based on the heading value obtained from the onCreate method. Is it possible?
Solution
Declare your TextView
…. at the class level
TextView heading;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.calculation);
heading = (TextView) findViewById(R.id.paper_name);
heading.setText("something");
......
Then access it in the onClick()
method as shown below….
@Override
public void onClick(View v)
{
int BLACK_AND_WHITE_MULTIUPLIER = 4200;
int COLOR_MULTIUPLIER = 6400;
switch (v.getId())
{
case R.id.btCalculate:
int multiplier = 0;
if (heading.getText().toString.equals("something")) {
multiplier = COLOR_MULTIUPLIER;
} else {
multiplier = BLACK_AND_WHITE_MULTIUPLIER;
}
int multiplier = rbColor.isChecked() ? COLOR_MULTIUPLIER
: BLACK_AND_WHITE_MULTIUPLIER;
int column = Integer.parseInt((String) spColumn
.getSelectedItem());
int inch = Integer.parseInt((String) spInch.getSelectedItem());
tvAmount.setText((multiplier * column * inch) + "");
break;
}
}