//首先在XML文件中配置一下 <TextView android:id="@+id/textViewId" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="数据" /> <Button android:id="@+id/butid" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="发送消息" android:layout_below="@id/textViewId" />
接下来重点是MainActivity中的代码段
public class MainActivity extends Activity { private Button but; private TextView textview; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); but=(Button)findViewById(R.id.butid); textview=(TextView)findViewById(R.id.textViewId); but.setOnClickListener(new ButList()); handler =new MyHandler(); } class ButList implements OnClickListener{ @Override public void onClick(View v) { NetWorkThread net=new NetWorkThread(); net.start(); } } class MyHandler extends Handler{ @Override public void handleMessage(Message msg) { //Toast.makeText(getApplicationContext(), Thread.currentThread().getName(), Toast.LENGTH_LONG).show(); String s=(String)msg.obj; textview.setText(s); } } class NetWorkThread extends Thread{ @Override public void run() { //模拟访问网络,所以当线程运行时,首先休眠2秒钟 //Toast.makeText(getApplicationContext(), Thread.currentThread().getName(), Toast.LENGTH_LONG).show();//得到当前线程的名字 try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } //模拟的数据 String s="从网络当中获取的数据"; //textview.setText(s);这样做是错误的,因为Android系统中,只有在Main Thread 中才能操作UI Message msg=handler.obtainMessage(); msg.obj=s; handler.sendMessage(msg); } }
这仅仅是模拟Handler的小Demo,仅供自己学习使用。谢谢大家。
时间: 2024-11-15 00:36:25