Reputation: 3
I am trying to get my app to display either a text or an image when two spinners selected values equal each other.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner sp1 =(Spinner)findViewById(R.id.sp1);
String txtFromSpinner1 = sp1.getSelectedItem().toString();
Spinner sp2 = (Spinner)findViewById(R.id.sp2);
String txtFromSpinner2 = sp2.getSelectedItem().toString();
if (txtFromSpinner1.equals(1)&& txtFromSpinner2.equals(2)){
TextView textElement = (TextView)findViewById(R.id.txResult);
textElement.setText("3");
}
}
}
Upvotes: 0
Views: 1381
Reputation: 3212
Try this:
Spinner sp1 =(Spinner)findViewById(R.id.sp1);
Spinner sp2 = (Spinner)findViewById(R.id.sp2);
TextView textElement = (TextView)findViewById(R.id.txResult);
Button showResult = (Button)findViewById(R.id.btnShowResult);
showResult.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String txtFromSpinner1 = sp1.getSelectedItem().toString();
String txtFromSpinner2 = sp2.getSelectedItem().toString();
if (txtFromSpinner1.equals("1")&& txtFromSpinner2.equals("2"))
textElement.setText("3");
}
});
Upvotes: 2
Reputation: 48278
txtFromSpinner1.equals(1)
is not going to work because you are comparing a string against a number and that will return false,
you need instead to compare the strings of the spinners.
...
txtFromSpinner1.equals(txtFromSpinner2)
OR using quotes in your literals
if (txtFromSpinner1.equals("1")&& txtFromSpinner2.equals("2")){
Upvotes: 0
Reputation: 12986
For comparing the two spinners selected values, you should use
String spinnerOne = mySpinnerOne.getSelectedItem().toString() ;
String spinnerTwo = mySpinnerTwo.getSelectedItem().toString() ;
Since spinnerOne
and spinnerTwo
are both java strings
, you should use the equals method to compare them.
if(spinnerOne.equals(spinnerTwo))
Finally, for handling the changes in the spinners selection, every time the user selects a new value, you should use onItemSelectedListener()
:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Upvotes: 0