0
プログラムのフロー中に、ハンドラを使用してTextViewを更新する方法を理解できません。私はこのハンドラとTextViewの更新問題
public class MainActivity extends AppCompatActivity {
TextView text;
boolean isReady; //boolean to check a new Message
String update; //String to send to TextView
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView);
Handler handler = new MyHandler(); //defined down
MyHandlerThread thr = new MyHandlerThread(handler); //defined in other .class file
thr.start();
for(int i=0;i<100;i++){ //a simple for
if(i%2==0)
thr.setMessage(i + ": Divisible for 2");
else
thr.setMessage(i+": Not Divisible for 2");
}
}
private class MyHandler extends Handler { //inner class
@Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
if(bundle.containsKey("refresh")) {
String value = bundle.getString("refresh");
text.setText(value);
}
}
}}
のような簡単なコードでそれをテストだし、これはちょうど最後の予測文字列「99:2のためdivibleない」印刷このコードスレッドコード
public class MyHandlerThread extends Thread {
private Handler handler;
private boolean isSent;
String text;
public MyHandlerThread(Handler handler) {
this.handler = handler;
isSent=false;
text="";
}
public void run() {
try {
while(true) {
if(isSent){
notifyMessage(text);
Thread.sleep(1000);
isSent=false;
}
}
}catch(InterruptedException ex) {}
}
public void setMessage(String str){
text=str;
isSent=true;
}
private void notifyMessage(String str) {
Message msg = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("refresh", ""+str);
msg.setData(b);
handler.sendMessage(msg);
}}
ある
私は実際の例にできますか?私はあなたのソリューションを試していますが、それは動作していないようです –