Today's blog is from the second edition of Guo Shen's First Line of Code
Like many other GUI libraries, android's child threads are insecure, meaning that if you want to update UI elements in your application, you must be on the main thread
Otherwise, problems will occur
So we wrote a simple demo that would crash
public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text=(TextView)findViewById(R.id.text); Button changeText=(Button)findViewById(R.id.change_text); changeText.setOnClickListener(this ); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.change_text: new Thread(new Runnable() { @Override public void run() { text.setText("haha"); } }).start(); break; default: break; } } }
As a result, jump and see logcat is because the UI is updated in the child thread
In this case, Android provides a set of asynchronous demagnetization processing mechanism, which perfectly solves the problem
Modify the code, and you've almost solved the problem
public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private TextView text; public static final int UPDATE_TEXT=1; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case UPDATE_TEXT: text.setText("haha"); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text=(TextView)findViewById(R.id.text); Button changeText=(Button)findViewById(R.id.change_text); changeText.setOnClickListener(this ); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.change_text: Message message=new Message(); message.what=UPDATE_TEXT; handler.sendMessage(message); break; default: break; } } }
Because this is written before Chapter Ten, let's review it together
Okay, get to the point