I am working on this android application:
A Button and a textField, the button click change the text of the textField.
So i want to add some animation to the button click by changing the text character by character and wait 100 millisecondes before adding each character.
But when I run the application and press the button, all the text appear after the sleep time without any animation :p
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for(int i=0 ; i<str.length() ; i++)
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
txt.append(String.valueOf(str.charAt(i)));
}
}
});
you do not want to sleep on the main-thread. Better use postDelayed
you block ui thread now and you only see the result of onClick. you should not call sleep in ui thread. this is not best, but it should work
#Override
public void onClick(View arg0) {
final Handler handler = new Handler();
new Thread() {
public void run() {
for (int i = 0; i < str.length(); i++) {
final int _i = i;
try {
Thread.sleep(100);
} catch (Exception e) {
}
handler.post(new Runnable() {
public void run() {
txt.append(String.valueOf(str.charAt(_i)));
}
});
}
}
}.start();
}
Related
Start Button...
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
start_stop = true;
thread.start();
chronometer.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
chronometer.start();
}
});
Stop Button...
btn_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chronometer.stop();
// 변수에 저장된 값 초기화!!
timeWhenStopped =0;
start_stop=false;
graph.removeAllSeries();
data = 0;
double[] resetted = new double[50];
saving = resetted;
if(thread !=null && thread.isAlive()) thread.interrupt();
i++;
}
});
And here is my thread in the same activity.
runnable = new Runnable() {
#Override
public void run() {
int j =i;
if(!thread.interrupted()){
for (int i = 0; i < 50; i++){
if(start_stop){
runOnUiThread(new Runnable() {
#Override
public void run() {
addEntry();
}
});
try {
Thread.sleep(600); //여기서 속도 제어할 수 있나봄!
} catch (InterruptedException e) {
// manage error ...
}
}
}
}
}
};
thread = new Thread(runnable);
So what I'm going to do is. I want to draw some line graph started with button Start, and then stop and clear with stop button.
and draw new graph again with start button.
But every time I tried re-start , application shut-down with error..
" Thread already started... "
So I think I need to kill or stop thread by clicking Stop button..
and I've tried several ways ... recommended... around here and I couldn't solve yet.
help me please..
(+ and I'm quite new here,,, and,,, my English isn't perfect.. also it's my first question.. sorry for any mistakes. thanks)
In my strings.xml I have 5 strings with text. And I want to be able to change the content of a TextView every 5 seconds.
Example:
First 5 seconds the TextView will show the content of the first string, then next five seconds it will show the second string. And after the fifth string it will show the first string again.
Sorry about this bad description, I'm new in Java.
Try this:
final TextView textView = yourTextView;
final int[] array = {R.string.text1, R.string.text2,R.string.text3,R.string.text4,R.string.text5};
textView.post(new Runnable() {
int i = 0;
#Override
public void run() {
textView.setText(array[i]);
i++;
if (i ==5)
i = 0;
textView.postDelayed(this, 5000);
}
});
new CountDownTimer(25000, 5000) {
public void onTick(long millisUntilFinished) {
mTextField.setText(//question here);
}
public void onFinish() {
mTextField.setText(//End of questions);
}
}.start();
For further Info see this -> http://developer.android.com/reference/android/os/CountDownTimer.html
You can use "Handler" in this
Create a handler in onCreate
`String[] arr = {R.string.value1, R.string.value2,R.string.value3,R.string.value4,R.string.value5};`
Handler mHandler = new Handler();
Now create one Thread and use while loop to periodically perform the task using the sleep method of the thread.
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<5;i++){
try {
Thread.sleep(5000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
textView.setText(arr[i])
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
As you can see in the pictures, toast line is working properly but process function not working another activity.
This code line does not workking on background, only work on Activity.
Process p = Runtime.getRuntime().exec("input touchscreen tap 500 500");
My purpose is touch the different screen, EX:WhatsApp or any app.
btndene.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.teamviewer.quicksupport.market");
startActivity(launchIntent);
for(int i = 0; i<10; i++) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
update(i);
}
}
private void update(final int i) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//txt.setText("Hello"+i);
// komut = "input keyevent 30";
//calistir(komut);
Toast.makeText(MainActivity.this,"Bastin",Toast.LENGTH_SHORT).show();
try {
p = Runtime.getRuntime().exec("input touchscreen tap 500 500");
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}).start();
Due to security reasons it wont work on other apps...You can use any UI automation frameworks like Robotium,Expresso to do this..
Try using monkeyrunner instead. It works with any app.
Trying to get the following ;
ImageView x is shown for y seconds. Then, x is Invisible again and a different ImageView (z) is shown for y seconds. And so on..
I've got :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.series_onthouden);
hideAllImages();
showImage(3, 2000);
showImage(4, 1000);
}
public void showImage(int color, final int sec) {
Thread thread = new Thread() {
#Override
public void run() {
try {
Thread.sleep(sec);
} catch (InterruptedException e) {
}
runOnUiThread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < myImagebtns.length; i++) {
((ImageView) findViewById(myImagebtns[i]))
.setVisibility(View.INVISIBLE);
}
}
});
}
};
if (!thread.isAlive()){
((ImageView) findViewById(myImagebtns[color])).setVisibility(View.VISIBLE);
thread.start();
}
}
It works for the first color.. But also shows the second simultaniously. The second color should be shown when the first turns invisible (after x seconds).
ty
You could try using a Handler like the example below:
Handler handler = new Handler();
im1.setVisibility(View.VISIBLE);
handler.postDelayed(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
im1.setVisibility(View.INVISIBLE);
im2.setVisibility(View.VISIBLE);
}
});
}
},500);
where 500 is the delay between events.
Repeat postDelayed calls for as many images as necessary.
Hope this helps!
Handler hnd = new Handler() {
#Override
public void handleMessage(Message msg) {
int id = sequence.get(msg.arg1);
if(msg.arg1 % 2 == 0) {
sq.get(id-1).setBackgroundResource(R.drawable.square_show);
} else {
sq.get(id-1).setBackgroundResource(R.drawable.square);
}
}
};
#Override
public void onResume() {
super.onResume();
Thread background = new Thread(new Runnable() {
public void run() {
try {
for(int i = 0; i < sequence.size()-1; i++) {
record_tv.setText(""+i);
Thread.sleep(200);
Message msg = hnd.obtainMessage();
msg.arg1 = i;
msg.sendToTarget();
}
} catch(Throwable t) {
}
}
});
background.start();
}
[CODE UPDATED] now it goes through the first loop and stops
do you have any idea why the code in the first runOnUiThread gets executed but it doesn't do what i want?
what i want is: change the image to "square", wait 2 seconds, change the image to "square_show", wait 2 secs and repeat the loop
i've been struggling for an hour now...
You can easily set image using following code.
sq.get(id-1).setImageResource(R.drawable.square_show);
sq.get(id-1).setImageResource(R.drawable.square);
public void show(int size) {
// CICLE THROUGH EACH SQUARE
for(int i = 0; i <= size-1; i++) {
Thread thrd = new Thread() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id-1).setImageResource(R.drawable.square_show);
// System.out.println("1st..........");
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sq.get(id-1).setImageResource(R.drawable.square);
// System.out.println("2nd..........");
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
};
thrd.start();
}
}
This is a wrong way to achieve it. This may help you.
http://developer.android.com/guide/topics/graphics/2d-graphics.html#tween-animation
I would suggest you to use a handler
int drawablebkg[] ={R.drawable.ic_launcher,R.drawable.icon};
Handler m_handler;
Runnable m_handlerTask ;
ImageView iv;
iv = (ImageView)findViewById(R.id.imageView1);
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
iv.setImageResource(android.R.color.transparent);
if(i<2)
{
ivsetBackgroundResource(drawablebkg[i]);
i++;
}
else
{
i=0;
}
m_handler.postDelayed(m_handlerTask, 2000);
}
};
m_handlerTask.run();
In onPause() of your activity
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//_t.cancel();
m_handler.removeCallbacks(m_handlerTask);
}
Another way
iv= (ImageView)findViewById(R.id.imageView1);
AnimationDrawable animation = new AnimationDrawable();
animation.addFrame(getResources().getDrawable(R.drawable.ic_launcher), 2000);
iv.setImageResource(android.R.color.transparent);
animation.addFrame(getResources().getDrawable(R.drawable.icon), 2000);
animation.setOneShot(false);
iv.setBackgroundDrawable(animation);
//set setBackgroundDrawable(animation) is decprecreated i guess. not sure in which api
// start the animation!
animation.start();
Another way
Define background.xml in drawable folder
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="#drawable/ic_launcher" android:duration="2000" />
<item android:drawable="#drawable/icon" android:duration="2000" />
</animation-list>
I your activity onCreate();
ImageView iv = (ImageView)findViewById(R.id.imageView1);
iv.setBackgroundResource(R.drawable.background);
AnimationDrawable animation= (AnimationDrawable)loadingRaven.getBackground();
loadingRaven.setImageResource(android.R.color.transparent);
animation.start();
Note to stop the animation you need to call animation.stop()
Because the resource changes in the UI thread and you are sleeping your background thread. The UI thread is running normally.
Use handlers:
public class MainActivity extends Activity {
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
}
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.arg1 % 2 == 0) {
b.setBackgroundResource(R.drawable.analytic_icon);
} else {
b.setBackgroundResource(R.drawable.ic_launcher);
}
}
};
#Override
public void onResume() {
super.onResume();
Thread background = new Thread(new Runnable() {
public void run() {
try {
for (int i = 0; i < 20; i++) {
Thread.sleep(2000);
Message msg = handler.obtainMessage();
msg.arg1 = i;
msg.sendToTarget();
}
} catch (Throwable t) {
// just end the background thread
}
}
});
background.start();
}
}
Try this,It will work:
public void show(final int size) {
Thread thrd = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i <= size - 1; i++) {
id = (Integer) sequence.get(i);
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id - 1).setBackgroundResource(
R.drawable.square_show);
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id - 1).setBackgroundResource(
R.drawable.square);
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thrd.start();
}