How can I change image after every 5 second in Android - java

I need to change image every 5 seconds, then when we touch the ImageView it will stop changing until we release the touch.
When the application go to OnPause state it pauses the auto changing of the image.
I save the KEY_ID and stop the runnable in onSaveInstanceState
How can I make this change automatically ? Below is my code in java.
public class MainActivity extends AppCompatActivity {
private ImageView im_car;
private Handler mHandler = new Handler();
public static Integer[] mThumbeId = {R.drawable.first, R.drawable.second, R.drawable.thard};
public int i = 0, id = 0;
private String KEY_ID = "key_id";
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
im_car = findViewById(R.id.im_car);
mThumbRun.run();
if (savedInstanceState != null) {
i = savedInstanceState.getInt(KEY_ID);
}
im_car.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mHandler.removeCallbacks(mThumbRun);
break;
case MotionEvent.ACTION_UP:
if (i!=0)
{
i = i-1;
}
else i=2;
mThumbRun.run();
break;
}
return false;
}
});
}
#Override
protected void onRestart() {
super.onRestart();
if (i!=0)
{
i = i-1;
}
else i=2;
mThumbRun.run();
}
Runnable mThumbRun = new Runnable() {
#Override
public void run() {
im_car.setImageResource(mThumbeId[i]);
i++;
if (i >= mThumbeId.length) {
i = 0;
}
mHandler.postDelayed(this, 5000);
}
};
}

You can create a touch listener in your imageview.
Keep a boolean to check wether image should change.
boolean imageChangePermission = true;
yourImageView.setOnTouchListener(new OnTouchListener () {
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
Log.d("TouchTest", "Touch down");
}
else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
Log.d("TouchTest", "Touch up");
imageChangePermission = false;
}
}
}
ACTION_DOWN - when you first touch
ACTION_MOVE - when you are moving your finger on screen
ACTION_UP - when you remove your finger from screen
Create a Handler to periodically call the change Image method of yours.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(imageChangePermission) {
changeImage();
}
}
},5000); //Run after every 5 second

Related

Show one message when a button is pressed and other one when is released. Android

I´m just trying to program a simple code that shows a message when the button is pressed and another one when is released.
I try this but it didn´t work:
btnOn.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
mmHandler.postDelayed(mAction1, 10);
break;
case MotionEvent.ACTION_UP:
mmHandler.removeCallbacksAndMessages(null);
mmHandler.postDelayed(mAction1, 10);
txtdebug.setText("Message 2");
break;
}
return true;
}
Runnable mAction1 = new Runnable() {
#Override
public void run() {
txtdebug.setText("Message 1");
//mHandler.postDelayed(this, 100);
}
};
Any idea of why the removeCallbacksAndMessages is not working. It displays for instance Message 2 when I released but then it appears again message 1. It didn´t keep like that.
I don't know If I understand You correctly but if You want to execute function every X milliseconds when the button is pressed and then when the user release button stop it You can do it like this (You were very close to this solution but You run Hendler again in UP event):
public class MainActivity extends AppCompatActivity
{
Button btnOn;
Handler handler;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = findViewById(R.id.btnOn);
handler = new Handler();
final Runnable action = new Runnable()
{
#Override
public void run()
{
Log.d("MyTag", "Run action");
handler.postDelayed(this, 100); // Run action every 100 ms
}
};
btnOn.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View view, MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
Log.d("MyTag", "Down");
handler.postDelayed(action, 10);
return true;
case MotionEvent.ACTION_UP:
Log.d("MyTag", "Up");
handler.removeCallbacksAndMessages(null);
return true;
default:
return false;
}
}
});
}
}

Android Java, setOnTouchListener delete 1 last character from string every 0.25s

I am making calculator on java. I want to make a button, which corresponds to delete the last character.
If you press on it for 1 second, it starts to delete 1 character every 0.25s form EditText string.
Clear button:
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(operation.length() != 0){
String s=operation.getText().toString();
s = s.substring(0,operation.length()-1);
operation.setText(s);}
}
});
Long touch idea:
clear.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
You can use ScheduledExecutorService to schedule Runnables at a set rate and with an initial delay. Here's how I would do it:
// Create member variables for your ExecutorService and ScheduledFuture
private ScheduledExecutorService mExecutor;
private ScheduledFuture<?> mFuture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
final EditText editText = findViewById(R.id.textView);
final Button button = findViewById(R.id.button2);
// Set up the ExecutorService
mExecutor = Executors.newSingleThreadScheduledExecutor();
final Runnable deleteRunnable = new Runnable() {
#Override
public void run() {
// We'll use the view's post() method
// to make sure we're updating it from the correct thread
editText.post(new Runnable() {
#Override
public void run() {
String textValue = editText.getText().toString();
if(textValue.length() > 0){
// Delete the last character
textValue = textValue.substring(0, textValue.length() - 1);
Log.d("MY_LOG_TAG", textValue);
editText.setText(textValue);
}
// (Optionally)
// Keep the cursor at the end of the text
editText.setSelection(textValue.length());
}
});
}
};
button.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch(action){
case MotionEvent.ACTION_DOWN:
Log.d("MY_LOG_TAG", "Action down");
// Schedule the runnable with an initial delay of 1000 milliseconds
// and at a rate of 250 milliseconds
mFuture = mExecutor.scheduleAtFixedRate(deleteRunnable, 1000, 250, TimeUnit.MILLISECONDS);
break;
case MotionEvent.ACTION_UP:
Log.d("MY_LOG_TAG", "Action up");
// Cancel the scheduled runnable when the Up event is triggered
if(mFuture != null){
mFuture.cancel(false);
}
break;
}
return false;
}
});
}
#Override
protected void onDestroy() {
// Shutdown the Executor Service
mExecutor.shutdown();
super.onDestroy();
}

A button that shows how long time it gets pressed

I wanna make a button that can show me how long time it gets pressed. If the button stops to get pressed the time still stays there, then you can keep pressing it. How can i do this?
With this code, I made a 5 second button-press open a new activity :)
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1=(Button)findViewById(R.id.button1);
final Handler handel = new Handler();
button1.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN:
handel.postDelayed(run, 5000/* OR the amount of time you want */);
break;
default:
handel.removeCallbacks(run);
break;
}
return true;
}
Runnable run = new Runnable() {
#Override
public void run() {
Intent i = new Intent(MainActivity.this, SecActivity.class);
startActivity(i);
}
};});
}}
if your mean a Button count the times it's pressed you can use:
int count = 0;
(your button).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
count++;
}
});
if you mean the longer you hold it you can use:
long time = 0;
(your button).setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == event.ACTION_DOWN){
time = System.currentTimeMillis();
}else if( event.getAcion() == event.ACTION_UP){
time = System.currentTimeMillis() - time;
}
return true;
}
});
note: that your variables like (int count) and (long time) should be declared in the body of your class not into a method;
below code is a example code for recognizing double click on a view with Custom time;
boolean isPressed = false;
long delayed = 1000;
final Hanlder handler = new Handler();
Button b;
b.setOnClickListener(new View.onClickListener(){
public void onClick(View v){
if(isPressed == true){
// recognize double click;
}else{
Toast.makeText(getApplicationContext(),"tap again to exit",1).show();
isPressed = true;
handler.postDelayed(new Runnable(){
public void run(){
isPressed = false;
}
},delayed);
}
});
Try TouchListener:
Handler handel = new Handler();
b.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN:
handel.postDelayed(run, 5000);
break;
default:
handel.removeCallbacks(run);
break;
}
return true;
}
});
Later define run:
Runnable run = new Runnable() {
#Override
public void run() {
// Your code to run on long click
}
};
Set a listener for when the button is pressed and when the button is released. Create a timer that records after the button is pressed and stops when the button is released. There should be listeners for both if you are using JFrame or Android as your GUI.

How to use an onTouchListener to do two different tasks from the same button

I'm trying to make two buttons that will change add or subtract 1 from a value when tapped, and constantly add or subtract 1 ten times per second while the button is held. I can get the value to be changed when the button is tapped, or when it is held, but I can't get the behavior I want. Here's what I have:
btPlus.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
setTempo(mTempo + 1);
mTempo=mTempo+1;
tvTempo.setText(Integer.toString(mTempo));
return true;
}
return false;
}
});
btMinus.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
setTempo(mTempo - 1);
mTempo=mTempo-1;
tvTempo.setText(Integer.toString(mTempo));
return true;
}
return false;
}
});
btPlus.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int action = motionEvent.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (getActivity() == null)
return;
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tvTempo.setText(Integer.toString(mTempo));
mTempo++;
if (mTempo > 300)
mTempo = 300;
}
});
}
}, 100, 100);
break;
case MotionEvent.ACTION_UP:
timer.cancel();
}
return true;
}
});
btMinus.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int action = motionEvent.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (getActivity() == null)
return;
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tvTempo.setText(Integer.toString(mTempo));
mTempo--;
if (mTempo < 1)
mTempo = 1;
}
});
}
}, 100, 100);
break;
case MotionEvent.ACTION_UP:
timer.cancel();
}
return true;
}
});
return rootView;
}
Thanks for your help!
You can implement onKeyListener to determine how long button is held, like in this example:
Android long-touch event
or use onLongClickListener to perform a different function from a regular "click" like here:
On long click delete item

Android: Toggle button doesnt update

I'm having some problems trying to set togglebutton (LeftLightButton) state and text after receiving value 1 at novo.charAt(0) for example. The main idea is, i click the button, it makes webview.loadUrl, and if the page changes to what i expected the toggle button state should be on, if not, it must stay off and vice versa. The way it is now, doesnt change the text neither state in case the site didnt update to the value that i was expecting.
public class MainActivity extends Activity {
private WebView webView;
private ToggleButton LeftLightButton;
private Thread webviewthread;
private String baseURL;
private boolean LeftLightButtonState;
public void onCreate(Bundle savedInstanceState) {
final Context context = this;
baseURL = "http://192.168.1.4/i.php";
LeftLightButton = (ToggleButton) findViewById(R.id.toggleButton1);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runOnUiThread(new Runnable() {
public void run()
{
synchronized(this) {
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(context, "HTMLOUT");
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
});
webView.loadUrl(baseURL);
}
}
});
showToast("Getting current status...");
}
public void notify(final boolean state, final ToggleButton buttonName) {
Thread thread = new Thread() {
#Override
public void run() {
synchronized (this) {
try {
wait(1000);
final ToggleButton button = (ToggleButton) findViewById(R.id.toggleButton1);
if (!state && button.isChecked()) {
showToast("Couldnt turn OFF");
// UI
runOnUiThread(new Runnable() {
#Override
public void run() {
button.setChecked(false);
button.setTextOff("OFF");
}
});
// end of UI
}
if (state && !button.isChecked()) {
showToast("Couldnt turn ON");
// UI
runOnUiThread(new Runnable() {
#Override
public void run() {
button.setChecked(true);
button.setTextOn("ON");
}
});
// end of UI
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
thread.start();
}
public void showToast(final String toast)
{
runOnUiThread(new Runnable() {
public void run()
{
Toast.makeText(MainActivity.this, toast, Toast.LENGTH_SHORT).show();
}
});
}
public void onClick(View arg0) {
final int id = arg0.getId();
switch (id) {
case R.id.toggleButton1:
if (LeftLightButtonState == true) {
webView.loadUrl(baseURL+"?L=0");
notify(false, LeftLightButton);
} else {
webView.loadUrl(baseURL+"?L=1");
notify(true, LeftLightButton);
}
break;
// even more buttons here
}
}
#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;
}
public void processHTML(String html) { // <html> <body> 1 0 0 0 </body> </html>
LeftLightButton = (ToggleButton) findViewById(R.id.toggleButton1);
String novo = android.text.Html.fromHtml(html).toString();
System.out.println("RECEIVED: "+novo);
if (novo != null) {
if (novo.charAt(0) == '0') {
LeftLightButtonState = false;
LeftLightButton.setTextOff("OFF");
LeftLightButton.setChecked(false);
}
if (novo.charAt(0) == '1') {
LeftLightButtonState = true;
LeftLightButton.setTextOn("ON");
LeftLightButton.setChecked(true);
}
System.out.println("CHEGUEI");
}
}
}
Use different string in the xml files itself. Then based on the state appropriate text will be displayed. You can call setChecked(true/false) to select or unselect the Toggle Button.. It is working fine in my project.
android:textOff="#string/dontshowtraffic"
android:textOn="#string/showtraffic"

Categories