fire_head fire_head - 2 months ago 17
Android Question

Constant listener for Boolean - Java Android

In my android app, I'm trying to check whether a boolean has changed and if it has then do something. But it's not constantly checking it. I believe I need a listener, but I'am unaware on how to structure it or where to put it. I've looked online and can really only find

onClick
s etc, no boolean ones.

Here is what I have so far:

public boolean gameStartTouch = false;
public boolean titleVisible = true;
/*
public boolean isJumping = false;
public boolean isGrounded = false;
*/

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_main);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
int eventaction = event.getAction();

switch (eventaction) {
case MotionEvent.ACTION_DOWN:
if (gameStartTouch == false) {

gameStartTouch = true;
titleVisible = false;
}
break;
}
return true;
}


and this is what needs to go in the listener:

ImageView titleView = (ImageView) findViewById(R.id.titleImg);
ImageView startNotifView = (ImageView) findViewById(R.id.startNotifImg);

if (titleVisible == false) {
titleView.setVisibility(View.INVISIBLE);
startNotifView.setVisibility(View.INVISIBLE);
} else {
titleView.setVisibility(View.VISIBLE);
startNotifView.setVisibility(View.VISIBLE);
}


Thanks in advance. I couldn't find much info on it for these circumstances specifically.

Answer

Do some modifying to your code, manage it like so

@Override
public boolean onTouchEvent(MotionEvent event) {
    int eventaction = event.getAction();

    switch (eventaction) {
    case MotionEvent.ACTION_DOWN:

        titleView.setVisibility(View.INVISIBLE);
        startNotifView.setVisibility(View.INVISIBLE);
        break;
    }
    return true;
}

I would put your findViewById() calls in onCreate to avoid unnecessary resource fetching. The only thing I see is that you are only actually switching your booleans once. Is there any other time you plan to reset gameStartTouch to false and titleVisible to true after the first touch?

Comments