package com.Android.xiong.handlertesttwo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
//吗的 不知怎么的Toast显示的是好像一定要点下图片 显示的才能在屏幕上看到效果
private EditText ed1;
private Button ok1;
private Button next;
private ImageView image1;
private Thread th;
private static int s=1;
private int iamges[] = { R.drawable.a3, R.drawable.a4 };
private final String DATA = "data";
// 实现Runnable接口
class Rub implements Runnable {
public Handler myHandler;
// 线程体
@Override
public void run() {
Looper.prepare();
myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
String ms = "";
if (msg.what == 0x123) {
int data = msg.getData().getInt(DATA);
//循环的时候界面依旧可以点击next按钮 这是本实例效果
for (int i = 0; i < data; i++) {
try {
//循环一次 暂停1秒
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
ms += String.valueOf(i) + " ";
Toast.makeText(getApplicationContext(), ms, Toast.LENGTH_LONG)
.show();
}
}
}
};
Looper.loop();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1 = (EditText) findViewById(R.id.ed1);
ok1 = (Button) findViewById(R.id.Ok);
next = (Button) findViewById(R.id.next);
image1 = (ImageView) findViewById(R.id.image1);
final Rub rub = new Rub();
//子线程中不能有UI组件进行操作
th = new Thread(rub);
// 启动线程
th.start();
ok1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Message msg = new Message();
msg.what = 0x123;
Bundle bundle = new Bundle();
bundle.putInt(DATA, Integer.parseInt(ed1.getText().toString()));
msg.setData(bundle);
rub.myHandler.sendMessage(msg);
}
});
//在UI线程中操作组件
next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
image1.setImageResource(iamges[s++% iamges.length] );
}
});
}
@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;
}
}
更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11
