package com.example.xdlichen.drawview; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { static final String UPPER_NUM ="upper"; EditText etNum; CalThread calThread; class CalThread extends Thread{ public Handler mHandler; public void run(){ Looper.prepare(); mHandler=new Handler(){ //定义处理消息的方法 public void handleMessage(Message msg){ if(msg.what==0x123){ int upper=msg.getData().getInt(UPPER_NUM); List<Integer> nums=new ArrayList<Integer>(); outer: for(int i=2;i<=upper;i++) { for(int j=2;j<=Math.sqrt(i);j++) { if(i!=2&&i%j==0){ continue outer; } } nums.add(i); } Toast.makeText(MainActivity.this,nums.toString(),Toast.LENGTH_LONG).show(); } } }; Looper.loop(); } } public void onCreate(Bundle saveInstanceState) { super.onCreate(saveInstanceState); setContentView(R.layout.activity_main); etNum = (EditText) findViewById(R.id.etNum); calThread = new CalThread(); calThread.start(); Button bn = (Button) findViewById(R.id.bn); bn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { cal(v); } }); } public void cal(View source) { Message msg = new Message(); msg.what = 0x123; Bundle bundle = new Bundle(); bundle.putInt(UPPER_NUM, Integer.parseInt(etNum.getText().toString())); msg.setData(bundle); calThread.mHandler.sendMessage(msg); } }
疯狂android handler书上例子更正
最新推荐文章于 2019-01-08 07:58:08 发布