Basically I need help with the if else statement below. It is for a toggle butto
ID: 3541783 • Letter: B
Question
Basically I need help with the if else statement below. It is for a toggle button making a light bulb turn on and off. I can get the toggle to turn it on. Where I am confused is how to turn it back off.
package csc122.project.lightbulb;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ImageView light_off;
private ImageView light_on;
private Button buttontoggle;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
light_off = (ImageView)findViewById(R.id.light_off);
light_on = (ImageView)findViewById(R.id.light_on);
buttontoggle = (Button)findViewById(R.id.buttontoggle);
light_off.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
//set light off to invisible
light_off.setVisibility(ImageView.INVISIBLE);
//set light on to visible
light_on.setVisibility(ImageView.VISIBLE);
return true;
}
});
light_on.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
light_on.setVisibility(ImageView.INVISIBLE);
light_off.setVisibility(ImageView.VISIBLE);
return true;
}
});
buttontoggle.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
//stuck here
{
if (buttontoggle.isPressed())
{light_on.setVisibility(ImageView.VISIBLE);
}
else
{light_off.setVisibility(ImageView.VISIBLE);
}
}});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Explanation / Answer
//Replace your if else code with thisif(light_on.getVisibility() == View.VISIBLE){ light_on.setVisibility(ImageView.INVISIBLE); light_off.setVisibility(ImageView.VISIBLE);} else if(light_off.getVisibility() == View.VISIBLE){ light_on.setVisibility(ImageView.VISIBLE); light_off.setVisibility(ImageView.INVISIBLE);}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.