两种方法:
1.view.post;
2.AsyncTask;
(1)java文件:
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.TextView;
public class MyActivity extends Activity {
private Button button2=null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Button button1=(Button) findViewById(R.id.button1);
TranslateAnimation animation=new TranslateAnimation(0,150,0,0);
animation.setRepeatCount(100);
animation.setDuration(2000);
button1.setAnimation(animation);
final Button button2=(Button)findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread2().execute();
}
/*方法一:v.post 可读性差,不易维护
public void onClick(final View v) {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
v.post(new Runnable() {
@Override
public void run() {
TextView view=(TextView) v;
view.setText(""+10);
}
});
}
}).start();
}*/
//方法二:AsyncTask方法
class Thread2 extends AsyncTask<String, Integer, Integer> {
protected void onPostExecute(Integer sum) {
button2.setText(""+10);
}
protected Integer doInBackground(String... url) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int sum =10;
return sum;
}
}
});
}
}
(2)xml文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MyActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:id="@+id/button1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="76dp"
android:layout_marginTop="61dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:id="@+id/button2"
android:layout_centerVertical="true"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button" />
</RelativeLayout>