利用Handler在子线程中更新UI
TestHandler.java
public class TestHandler extends Activity { static final String UPPER_NUM="upper"; private CalThreand calThreand; EditText editText; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_handler); editText=(EditText)findViewById(R.id.handler_parText1); textView=(TextView)findViewById(R.id.handler_text); calThreand=new CalThreand(); calThreand.start(); Button sendButton=(Button)findViewById(R.id.handler_sendButton); sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String str=editText.getText().toString(); if(str==null||str.equals("")) return ; Message msg=new Message(); msg.what=0x123; Bundle bundle=new Bundle(); bundle.putInt(UPPER_NUM,Integer.parseInt(str)); msg.setData(bundle); calThreand.mHandler.sendMessage(msg); } }); } class CalThreand extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler=new Handler() { @Override public void handleMessage(Message msg){ if(msg.what==0x123){ int upper=msg.getData().getInt(UPPER_NUM); final List<Integer>nums=new ArrayList<Integer>(); for(int i=1;i<=upper;i++) nums.add(i); runOnUiThread(new Runnable() { @Override public void run() { textView.setText(nums.toString()); } }); } } }; Looper.loop(); } } }
activity_test_handler.xml
<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" > <TableRow android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <EditText android:inputType="number" android:hint="a:" android:id="@+id/handler_parText1" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" /> <EditText android:inputType="number" android:hint="b:" android:id="@+id/handler_parText2" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> </LinearLayout> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/handler_sendButton" android:text="send" android:background="@drawable/send_button_selector" android:layout_width="match_parent" android:textColor="#ffffff" android:textSize="30sp" android:layout_height="wrap_content"/> </TableRow> <TextView android:id="@+id/handler_text" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:textSize="25sp" /> </LinearLayout>
版权声明:本文为博主原创文章,未经博主允许不得转载。