Handler - exemplo simples |
Top Previous Next |
Tela RandlerActivity.java
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast;
public class RandlerActivity extends Activity implements OnClickListener {
protected static final int MENSAGEM_TESTE = 1; private Handler handler = new TesteHandler();
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1); b.setOnClickListener(this); }
public void onClick(View arg0) { // cria uma msg com delay de 3 seg Message msg = new Message(); msg.what = MENSAGEM_TESTE; // envia handler.sendMessageDelayed(msg, 3000); }
// handler utilizado para receber a msg private class TesteHandler extends Handler {
@Override public void handleMessage(Message msg) {
// what identifica msg if (msg.what == MENSAGEM_TESTE) { Toast.makeText(RandlerActivity.this, "mensagem!", Toast.LENGTH_SHORT).show(); } }
} }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Atualizar texto em 3 seg" />
</LinearLayout> |