「Android/非同期処理/HandlerRunnable」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→サンプル(Runnableクラス切り分け)) |
|||
行1: | 行1: | ||
+ | ==サンプル== | ||
+ | <pre> | ||
+ | final TextView textView = findViewById(R.id.text1); | ||
+ | final Handler handler = new Handler(Looper.getMainLooper()); | ||
+ | new Thread(new Runnable() { | ||
+ | @Override | ||
+ | public void run() { | ||
+ | final String msg = "background exec"; | ||
+ | if (handler != null) { | ||
+ | handler.post(new Runnable() { | ||
+ | @Override | ||
+ | public void run() { | ||
+ | if (textView != null) { | ||
+ | textView.setText(msg); | ||
+ | } | ||
+ | } | ||
+ | }); | ||
+ | } | ||
+ | } | ||
+ | }).start(); | ||
+ | </pre> | ||
参考:https://qiita.com/8yabusa/items/f8c9bb7eb81175c49e97 | 参考:https://qiita.com/8yabusa/items/f8c9bb7eb81175c49e97 | ||
2020年8月7日 (金) 16:02時点における版
サンプル
final TextView textView = findViewById(R.id.text1); final Handler handler = new Handler(Looper.getMainLooper()); new Thread(new Runnable() { @Override public void run() { final String msg = "background exec"; if (handler != null) { handler.post(new Runnable() { @Override public void run() { if (textView != null) { textView.setText(msg); } } }); } } }).start();
参考:https://qiita.com/8yabusa/items/f8c9bb7eb81175c49e97
サンプル(Runnableクラス切り分け)
MainActivity.java
final TextView textView = findViewById(R.id.text1); final Handler handler = new Handler(Looper.getMainLooper()); MyRunnableTask task = new MyRunnableTask(handler, textView); new Thread(task).start(); <pre> MyRunnableTask.java <pre> import android.os.Handler; import android.widget.TextView; public class MyRunnableTask implements Runnable { Handler mHandler; TextView mTextView; public MyRunnableTask(Handler handler, TextView textView) { mHandler = handler; mTextView = textView; } public void run() { final String msg = "background exec"; if (mHandler != null) { mHandler.post(new Runnable() { @Override public void run() { if (mTextView != null) { mTextView.setText(msg); } } }); } } }