I have a button and two images, i want the default image for the button to be btn1.jpg and when the button is clicked, the image should immediately change to btn2.jpg and after 3 seconds, it should again revert back to btn1.jpg. please tell me how do i achieve this?
package com.example.btn;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
private View ButtonName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void yolo(View v) {
switch (v.getId()) {
case R.id.buttonName:
ButtonName.setBackgroundResource(R.drawable.btn2);
//Disable click on Button
ButtonName.setEnabled(false);
try {
Thread.sleep(3000);
}
catch (Exception e) {
e.printStackTrace();
}
ButtonName.setBackground(getResources().getDrawable(R.drawable.btn1));
break;
case default:
ButtonName.setBackgroundResource(R.drawable.btn1);
}
}
}
You must change the button background image in the OnClick method to btn2.jpg. After that, you must start a timer to count down 3 seconds and, after that, change again the button image to btn1.jpg
private final int interval = 3000;
private Handler handler = new Handler();
private Runnable runnable
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
btn.setBackground(getResources().getDrawable(R.drawable.btn2))
//Start runnable after 3 seconds
handler.postDelayed(runnable, interval);
}
});
runnable = new Runnable(){
public void run() {
btn.setBackground(getResources().getDrawable(R.drawable.btn1))
}
};
finally figured it out myself!
Set background for button in xml
use this code:
package com.example.btn;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
public class MainActivity extends Activity {
Handler mHandler; // global instance
Runnable your_runnable; // global instance
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void yolo(final View view) {
if (view == view) {
view.setBackgroundResource(R.drawable.btn1);
mHandler = new Handler();
your_runnable = new Runnable() {
#Override
public void run() {
view.setBackgroundResource(R.drawable.btn2);
}
};
mHandler.postDelayed(your_runnable, 3000L);// 3sec timer
}
}
}
This may work for you!!
public class MainActivity extends Activity {
Button button;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.yourbuttonid);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
button.setBackgroundResource(getresources().getDrawable(R.drawable.btn1));
handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
button.setBackgroundResource(getresources().getDrawable(R.drawable.btn2));
}
}, 3000);
}
});
}
Ok so first, you have a mistake here :
ButtonName.setBackgroundResource(getresources().getDrawable(R.drawable.btn2));
And after, add a clickListener on your button :
private Thread t = new Thread(new Runnable {
#Override
public void run() {
ButtonName.setBackgroundResource(getresources().getDrawable(R.drawable.btn2));
//Disable click on Button
ButtonName.setEnabled(false);
try {
Thread.sleep(3000);
}
catch (Exception e) {
e.printstacktrace();
}
ButtonName.setBackgroundResource(getresources().getDrawable(R.drawable.btn1));
}
});
ButtonName.setOnClickListener (new OnClickListener (
#Override
public void onClick(View v) {
t.start();
}
));
I think it is what you want
Related
I've implemented a CountDownTimer in my code as follows: At the top of the class, I create
CountDownTimer myTimer;
Then when a user presses button Start, the following method is called:
private void countme()
{
final int tick = 500;
final int countTime = 10000;
myTimer = new CountDownTimer(countTime, tick) {
#Override
public void onTick(final long millisUntilFinished) { }
#Override
public void onFinish() {
myPicture.setVisibility(View.GONE);
}
};
myTimer.start();
}
I have button Stop all myTimer.cancel(). As you can see, if the timer is not cancelled, myPicture will disappear.
Even if I click the stop button so that myTimer.cancel() is called (I checked this with log statements), the counter still continues to count down and to make the picture disappear when it's done.
Why isn't it stopping? How do I get it to actually cancel?
To clarify, I do know how to implement Runnable timers, but they are not as accurate for my needs as CountDownTimers are, which is why I'm not using them in this case.
After a lot of tries, trick is to declare the timer in onCreate but start and cancel it in some other method. The onFinish() will not call after cancelling the timer.
myTimer = new CountDownTimer(COUNT_DOWN_TIME, TICK) {
#Override
public void onTick(final long millisUntilFinished) {
((TextView) findViewById(R.id.textView3)).setText(""
+ millisUntilFinished);
}
#Override
public void onFinish() {
findViewById(R.id.timer_imageBiew).setVisibility(View.GONE);
}
};
private fun startTimer() {
myTimer .start()
}
private fun stopTimer() {
myTimer .cancel()
}
Here in your method countme() you are initializing myTimer, so outside this method myTimer has no value.
Use this
Declare at the top
CountDownTimer myTimer;
final int tick = 500;
final int countTime = 10000;
In the onCreate method of Activity or Fragment
myTimer = new CountDownTimer(countTime, tick) {
#Override
public void onTick(final long millisUntilFinished) { }
#Override
public void onFinish() {
myPicture.setVisibility(View.GONE);
}
};
Now use myTimer.start() to start and myTimer.cancel() to stop it.
Hope you understood.
Your post is very odd. I just tried doing a sample activity:
public class MainActivity extends AppCompatActivity {
CountDownTimer myTimer;
Button btnStart;
Button btnCancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample2);
btnStart = (Button) findViewById(R.id.start);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countme();
Toast.makeText(MainActivity.this, "Count Started!", Toast.LENGTH_SHORT).show();
}
});
btnCancel = (Button) findViewById(R.id.cancel_timer);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myTimer.cancel();
Toast.makeText(MainActivity.this, "Clicked Stop Timer!", Toast.LENGTH_SHORT).show();
}
});
}
private void countme() {
final int tick = 500;
final int countTime = 10000;
myTimer = new CountDownTimer(countTime, tick) {
#Override
public void onTick(final long millisUntilFinished) {
Log.d(MainActivity.class.getSimpleName(), "onTick()");
}
#Override
public void onFinish() {
// myPicture.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "In onFinish()", Toast.LENGTH_SHORT).show();
}
};
myTimer.start();
}
}
It works perfectly fine. It stops the timer. But I went and looked around and found this answer where it mentions that CountDownTimer doesn't seem to work, so he suggested to use a Timer instead. Do check it out. Cheers!
This is working example , I have implemented both handler and timer you can pick one .
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class MainActivity extends Activity {
private CountDownTimer myTimer;
final int TICK = 500;
final int COUNT_DOWN_TIME = 2000;
// Option 2 using handler
private Handler myhandler = new Handler();
private Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Option 1 using timer
myTimer = new CountDownTimer(COUNT_DOWN_TIME, TICK) {
#Override
public void onTick(final long millisUntilFinished) {
((TextView) findViewById(R.id.textView3)).setText(""
+ millisUntilFinished);
}
#Override
public void onFinish() {
findViewById(R.id.timer_imageBiew).setVisibility(View.GONE);
}
};
// Option 2 using handler
runnable = new Runnable() {
#Override
public void run() {
findViewById(R.id.handlerImageView).setVisibility(View.GONE);
}
};
findViewById(R.id.start_timer).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
// Option 1 using timer
myTimer.start();
// Option 2 using handler
myhandler.postDelayed(runnable, COUNT_DOWN_TIME);
}
});
findViewById(R.id.stop_timer).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Option 1 stop timer
myTimer.cancel();
// Option 2 stop handler
myhandler.removeCallbacks(runnable);
}
});
}
}
I have three layouts:
Layout1
-->onClick()-->show
Layout2
-->wait three seconds-->show
Layout3
The problem is that Layout2 is not shown. To set the layouts I use
setContentView(int);
The relevant code might be:
public class TrainingActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
final Button inputButton = (Button)findViewById(R.id.inputButton);
inputButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
changeLayouts();
}
});
}
public void changeLayouts() {
setContentView(R.layout.layout2);
try {
TimeUnit.MILLISECONDS.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
setContentView(R.layout.layout3);
}
}
My idea was that Android might use something like an "Event-Loop" (like Qt) and my method would block the control to get back to the "Event-Loop" which would make the layout displayed.
But I couldn't find my error.
The problem why your layout2 is not shown is because of TimeUnit.MILLISECONDS.sleep(3000); - what you are doing here is you put your UI thread into sleep, so UI thread cannot process your request to change layout. And when it wakes up - it immediately sets layout3 that's why layout2 is not shown.
You might consider using Handler.postDelayed(Runnable, long) to postpone execution
So this should work as you expected:
public class TrainingActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
final Button inputButton = (Button)findViewById(R.id.inputButton);
inputButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
changeLayouts();
}
});
}
public void changeLayouts() {
setContentView(R.layout.layout2);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
setContentView(R.layout.layout3);
}
}, 3000);
}
}
Try this, it will surely work
public void changeLayouts() {
setContentView(R.layout.layout2);
Thread Timer = new Thread(){
public void run(){
try{
sleep(3000);
} catch(InterruptedException e){
e.printStackTrace();
} finally {
setContentView(R.layout.layout3);
}
}
}; Timer.start();
}
I'm trying to add background music to my application. All I want is the sound should played on pressing the btnoptn Button and its text transitions into the "music off". The music should continue on any Activity until the settings page is returned to and the same Button is pressed again. The music then stops and the Button text changes to "music on".
This my code so far:
package hello.english;
import hello.english.R;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.media.MediaPlayer;
import android.os.Bundle;
public class welcome extends Activity implements OnClickListener{
private Button btnoptn;
private Button btnmenu;
public static MediaPlayer mp2;
private void btnoptn(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button testButton = (Button) findViewById(R.id.btnoptn);
testButton.setTag(1);
testButton.setText("Musik Of");
mp2=MediaPlayer.create(this, R.raw.guitar_music);
mp2.start();
mp2.setLooping(true);
testButton.setOnClickListener( new View.OnClickListener() {
public void onClick (View v) {
final int status =(Integer) v.getTag();
if(status == 1) {
mp2.start();
mp2.setLooping(true);
testButton.setText("Musik Of");
v.setTag(0); //pause
} else {
mp2.pause();
testButton.setText("Musik On");
v.setTag(1);
} //pause
}
});
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
btnoptn=(Button)findViewById(R.id.btnoptn);
btnmenu=(Button)findViewById(R.id.btnmenu);
btnoptn.setOnClickListener( new View.OnClickListener() {
public void onClick(View view) {
btnoptn(null);
}
});
btnmenu.setOnClickListener( new View.OnClickListener() {
public void onClick(View view2) {
btnmenu();
}
});
}
protected void btnmenu() {
try {
Intent btnmenu= new Intent (this, menuenglish.class);
startActivity(btnmenu);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onStart() {
super.onStart();
btnoptn.setTag(0);
}
public void onClick(View view2) {
// TODO Auto-generated method stub
}
}
This is a really simple example. I don't know how it works if you switch between Activities, i never really worked with the MediaPlayer class.
public class MainActivity extends Activity
{
private MediaPlayer mediaPlayer;
private Button musicButton;
private OnClickListener listener = new OnClickListener()
{
// a boolean value in the names Onclicklistener class.
// this will help us to know, if the music is playing or not.
boolean isPlaying = false;
#Override
public void onClick(View arg0)
{
if(isPlaying)
{
mediaPlayer.pause(); //stop the music
musicButton.setText("Start"); //change the buttons text
}
else
{
mediaPlayer.start(); //start the music
musicButton.setText("Stop"); //change the text
}
//changing the boolean value
isPlaying = !isPlaying;
}
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Creating the mediaplayer with a desired soundtrack.
mediaPlayer = MediaPlayer.create(this, R.raw.my_music);
//Getting the Button reference from the xml
musicButton = (Button) findViewById(R.id.music_button);
//Setting the listener
musicButton.setOnClickListener(listener);
}
}
I am trying to display a progress bar using threading .. I accept that I do not have that much concept of threading.
Here is the code
public class Progress extends Activity {
static String[] display;
private static final int Progress = 0;
private ProgressBar mProgress;
private int mProgressStatus = 0;
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.progress);
mProgress = (ProgressBar) findViewById(R.id.progressBar);
// Start lengthy operation in a background thread
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
mProgressStatus = doWork();
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
}
private int doWork() {
display = new Logic().finaldata();
// TODO Auto-generated method stub
return 100;
}
}).start();
}
}
On running, the logcat message is
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
What is the mistake that I am doing here?
So your problem will be elsewhere. I tried your example with Handler and it works for me.
package com.sajmon.threadsDemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ThreadsDemoActivity extends Activity {
ProgressBar bar;
TextView label;
Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bar = (ProgressBar) findViewById(R.id.progBar);
new Thread(new Runnable() {
int i = 0;
int progressStatus = 0;
public void run() {
while (progressStatus < 100) {
progressStatus += doWork();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
handler.post(new Runnable() {
public void run() {
bar.setProgress(progressStatus);
i++;
}
});
}
}
private int doWork() {
return i * 3;
}
}).start();
}
}
And XML:
<ProgressBar
android:id="#+id/progBar" style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
So look at this and edit your code similar with this.
Find the below example code for progress bar update using threads
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ThreadDemo1ProgressBar extends Activity
{
ProgressBar bar;
TextView msgWorking;
boolean isRunning = false;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
bar.incrementProgressBy(5);
if (bar.getProgress() == bar.getMax()) {
msgWorking.setText("Done");
bar.setVisibility(View.INVISIBLE);
} else {
msgWorking.setText("Working..." +
bar.getProgress());
}
}// handleMessage
};
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
bar = (ProgressBar) findViewById(R.id.progress);
bar.setMax(100);
msgWorking = (TextView) findViewById(R.id.TextView01);
}
public void onStart() {
super.onStart();
bar.setProgress(0);
Thread background = new Thread(new Runnable() {
public void run() {
try
{
for (int i = 0; i < 20 && isRunning; i++) {
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch(Throwable t) {
// just end the background thread
}
}
});
isRunning = true;
background.start();
}// onStart
public void onStop() {
super.onStop();
isRunning = false;
}
}// ThreadDemo1ProgressBar
The about example updating the progress bar for every 5 seconds.
I actually just create a thread instance once and it works anyway. This code was written in the Startup Activity. All you need to do is call showSpinner1() method to show/hide the spinner.
Ensure to do this
getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS); in your onCreate() method and use this code for toggling the spinner ON and OFF.
// Spinner related code - The thread is created just once and is used multiple times (works!!)
boolean toShow = false;
Thread spinner1Thread = new Thread("Show/Hide Spinner Thread") {
#Override
public void run() {
setProgressBarIndeterminateVisibility(toShow);
}
};
/**
* Shows and hides the spinner
* #param pShow
*/
public void showSpinner1(boolean pShow) {
toShow = pShow;
runOnUiThread(spinner1Thread);
}
I would like to implement a SplashScreen in my app. I found the best and easiest way is to launch an activity that shows a layout with an image view at the launch of the app and then adding android:noHistory="true" attribute to the manifest.
Now, how do I set the splashscreen activity to launch the MainActivity class after a certain amount of time? Lets say 2 seconds?
This is my splashscreen activity
public class SplashActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
}
}
use
handler.postDelayed(runnable, delayinmilliseconds(2000 in your case));
final Runnable runnable = new Runnable()
{
public void run()
{
//start the new activity here.
}
};
Here is a complete sample.
package com.test.splash;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
public class splash extends Activity {
private static final int STOPSPLASH = 0;
//time in milliseconds
private static final long SPLASHTIME = 3000;a
private ImageView splash;
//handler for splash screen
private Handler splashHandler = new Handler() {
/* (non-Javadoc)
* #see android.os.Handler#handleMessage(android.os.Message)
*/
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case STOPSPLASH:
//remove SplashScreen from view
splash.setVisibility(View.GONE);
break;
}
super.handleMessage(msg);
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
splash = (ImageView) findViewById(R.id.splashscreen);
Message msg = new Message();
msg.what = STOPSPLASH;
splashHandler.sendMessageDelayed(msg, SPLASHTIME);
}
}
public class TrackMyMoneyActivity extends Activity {
//member fields
private ProgressBar pbar = null;
private TextView counter_txt = null;
Thread splash_thread = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pbar = (ProgressBar) findViewById(R.id.splashpbar);
counter_txt = (TextView) findViewById(R.id.countertxt);
//define thread
splash_thread = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
for( i=0;i<100;i++){
pbar.setProgress(i);
// counter_txt.setText(i+" %");
try {
splash_thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(i==100){
Intent intent = new Intent(getBaseContext(), LoginApp.class);
startActivity(intent);
}
}
});
splash_thread.start();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
I hope it will be solved your solution.
You can also use java.util.Timer in this way:
new Timer().schedule(new TimerTask(){
public void run() {
startActivity(new Intent(SplashActivity.this, MainActivity.class));
}
}, 2000 /*amount of time in milliseconds before execution*/ );
public class Splashscreen extends Activity
{
private static final int SPLASH_TIME = 10 * 1000;// 3 seconds
Button logo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splashscreen);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
try {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent intent = new Intent(Splashscreen.this,MainActivity.class);
startActivity(intent);
Splashscreen.this.finish();
//overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
}, SPLASH_TIME);
new Handler().postDelayed(new Runnable() {
public void run() {
}
}, SPLASH_TIME);
} catch(Exception e){}
// METHOD 1
/****** Create Thread that will sleep for 5 seconds *************/
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 5 seconds
sleep(50*1000);
// After 5 seconds redirect to another intent
Intent i=new Intent(getBaseContext(),MainActivity.class);
startActivity(i);
//Remove activity
finish();
} catch (Exception e) {
}
}
};
background.start();
}