Android开发之初级开发_异步回调机制Handler
在Android编程中,我们会遇到这种情况,那就是会经常的更新UI。但是Android规定,在UI线程中执行耗时的操作是不被允许的。
这时我们该怎么办呢?
这时我们就要用到异步回调机制Handler
下面是一个非常简单的demo
<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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.hql.handler.MainActivity$PlaceholderFragment" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> <Button android:id="@+id/btn_sure" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="改变" /> </RelativeLayout>
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { private TextView tv_show; private Button btn_sure; private static final int update = 1; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_main); btn_sure = (Button) findViewById(R.id.btn_sure); tv_show = (TextView) findViewById(R.id.text); btn_sure.setOnClickListener(new OnClickListener() { public void onClick(View v) { new Thread(new Runnable() { public void run() { Message message = new Message(); message.what = update; handler.sendMessage(message); } }).start(); } }); } private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case update: tv_show.setText("UI更新成功!"); break; default: break; } }; }; }

浙公网安备 33010602011771号