Reputation: 53
I currently have a strange problem when it comes to using booleans
in android. I first define the boolean, but when I use it, it does not return the correct value. Take the following code:
public class Prompt3 extends Activity {
boolean item1connect;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prompt3);
touchLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
if (Math.abs(startcoordinatesX - itemvar1x)<touchAllowance && Math.abs(startcoordinatesY - itemvar1y)<touchAllowance) {
item1connect = true;
}
if (item1connect = true) {
indic1.setBackground(getResources().getDrawable(R.drawable.ring_filled_standard));
}
}
}
});
}
When I do the above, indic1.setBackground
will setBackground
, regardless of if (Math.abs(startcoordinatesX - itemvar1x)<touchAllowance && Math.abs(startcoordinatesY - itemvar1y)<touchAllowance)
. However, when I try
if (Math.abs(startcoordinatesX - itemvar1x)<touchAllowance && Math.abs(startcoordinatesY - itemvar1y)<touchAllowance) {
indic1.setBackground(getResources().getDrawable(R.drawable.ring_filled_standard);
}
and bypass the boolean
item1connect
altogether, the code works just fine. How can I fix this while including the boolean
?
Thanks in advance
Upvotes: 0
Views: 97
Reputation: 456
What you're doing is telling itemiconnect to set its value to true
. Use the ==
operator to compare whether an item is true or false, or simply place itemiconnect
into the parentheticals and it will check for you.
EDIT: Where your code says
if (item1connect = true) {
indic1.setBackground(getResources().getDrawable(R.drawable.ring_filled_standard));
}
you can change this to the comparator
if (item1connect == true) {
indic1.setBackground(getResources().getDrawable(R.drawable.ring_filled_standard));
}
or better yet just use the implied true functionality
if (item1connect) {
indic1.setBackground(getResources().getDrawable(R.drawable.ring_filled_standard));
}
Java allows you to simply call your boolean in an "if" statement as it represents a true or a false value.
Upvotes: 1
Reputation: 147
You wrote
if (item1connect = true) {...}
This is an assignment, not a comparison. The return value of this assignment is true
so it looks like it doesn't work. Just write
if (item1connect == true) {...}
Or even, simply
if (item1connect) {...}
Upvotes: 4