Skip to content

Instantly share code, notes, and snippets.

@SZooo
Last active August 29, 2015 14:05
Show Gist options
  • Save SZooo/2947259d43c1dc497832 to your computer and use it in GitHub Desktop.
Save SZooo/2947259d43c1dc497832 to your computer and use it in GitHub Desktop.
在学Handler
public class HandlerTest extends Activity{
private Button button ;
private TextView view;
private Handler handler;
protected void onCreat(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.testView);
button = (Button) findViewById(R.id.btn);
view = (TextView) findViewById(R.id.tv);
handler = new myHandler();
button.setOnClickListener(new btnListener());
}
class buttonListener implements View.OnClickListener{
public void onClick(View v) {
Thread thread = new networkThread();
thread.start();
}
}
class networkThread extends Thread{
public void run(){
System.out.println("network---->" + Thread.currentThread().getName());
try {
Thread.sleep(20);
} catch (Exception e) {
e.printStackTrace();
}
String s = "从网络当中读取数据";
Message msg = handler.obtainMessage();
msg.obj = s;
handler.sendMessage(msg);
}
}
class myHandler extends Handler{
public void handleMessage(Message msg) {
System.out.println("Handler----->" + Thread.currentThread().getName());
String s = (String) msg.obj;
view.setText(s);
}
}
}
<LinearLayout 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:orientation="vertical"
tools:context="${relativePackage}.${activityClass}">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="数据"
/>
<Button
android:id="@+id/btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="发送数据"
/>
</LinearLayout>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment