Android/Java
[Java] Handler.post
혀가 길지 않은 개발자
2020. 6. 27. 15:36
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="혀가 길지 않은 개발자"
android:textSize="30dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
<Button
android:id="@+id/btnChange"
android:layout_width="180dp"
android:layout_height="80dp"
android:text="Change"
android:textSize="16dp"
android:layout_marginTop="30dp"
app:layout_constraintTop_toBottomOf="@+id/tvText"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java
package com.jwsoft.javaproject;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView tvText;
Button btnChange;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvText = findViewById(R.id.tvText);
btnChange = findViewById(R.id.btnChange);
btnChange.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
tvText.setText("혀가 긴 개발자");
}
}).start();
}
});
}
}


UI 작업은 무조건 메인쓰레드에서 해야됨.
Handler.post 사용해서 해결하자.
MainActivity.java
package com.jwsoft.javaproject;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView txtView;
Button btnChange;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtView = findViewById(R.id.txtView);
btnChange = findViewById(R.id.btnChange);
btnChange.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Handler().post(new Runnable() {
@Override
public void run() {
txtView.setText("혀가 긴 개발자");
}
});
}
});
}
}
