Android TextView에서 텍스트를 변경하는 방법
나는 이것을 시도했다
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t=new TextView(this);
t=(TextView)findViewById(R.id.TextView01);
t.setText("Step One: blast egg");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.setText("Step Two: fry egg");
하지만 어떤 이유로 실행하면 두 번째 텍스트 만 표시됩니다. 나는 그것이 Thread.sleep()
방법 차단 과 관련이 있다고 생각합니다 . 누군가가 "비동기 적으로"타이머를 구현하는 방법을 보여줄 수 있습니까?
감사.
이 답변을 android-discuss Google 그룹에 게시했습니다.
그런 다음 사용하는 것이 좋습니다 "튀김 달걀 : 폭발 계란 2 단계 1 단계를"당신은 그냥 표시하도록 뷰에 텍스트를 추가하려는 경우 t.appendText("Step Two: fry egg");
대신t.setText("Step Two: fry egg");
TextView
시작할 때 "1 단계 : 계란을 튀기다"라고 표시되고 나중에 "2 단계 : 계란 튀김"이라고 표시되도록 내용을 완전히 변경하려면 항상
실행 가능한 예제 sadboy가 준
행운을 빕니다
귀하의 onCreate()
방법에는 몇 가지 큰 결함이 있습니다.
1) 활동을 onCreate
준비 합니다- 이 방법이 완료 될 때까지 여기에서 수행하는 작업 은 사용자에게 표시 되지 않습니다 ! 예를 들어 , 마지막 변경 사항 만 그려져 사용자에게 표시되므로 TextView
여기서의 텍스트를 한 번 이상 변경할 수 없습니다!
2) Android 프로그램은 기본적으로 하나의 스레드에서만 실행 됩니다. 따라서 UI를 담당하는 주 스레드 Thread.sleep()
또는 사용하지 마십시오 Thread.wait()
! ( 자세한 내용은 "앱 반응 형 유지" 를 참조하십시오!)
무엇 당신의 초기화 하여 활동의가하는 것은 :
- 이유없이 새
TextView
개체 를 만듭니다t
! - 나중에
TextView
변수에서 레이아웃을 선택합니다t
. - 당신은 텍스트를 설정합니다
t
(하지만 명심하십시오 : 그것은 완료되고 응용 프로그램의 메인 이벤트 루프가 실행 된 후에 만 표시onCreate()
됩니다!) - 메서드 내 에서 10 초 동안 기다립니다. 모든 UI 활동을 중지하고 ANR을 강제로 강제 하므로 절대로 수행해서는 안됩니다 (애플리케이션이 응답하지 않음, 위 링크 참조).
onCreate
- 그런 다음 다른 텍스트를 설정합니다.이 텍스트는
onCreate()
메서드가 완료되고 다른 여러 활동 수명주기 메서드가 처리 되는 즉시 표시됩니다 !
해결책:
텍스트를 한 번만 설정하십시오
onCreate()
. 표시되어야하는 첫 번째 텍스트 여야합니다.만들기
Runnable
및Handler
private final Runnable mUpdateUITimerTask = new Runnable() { public void run() { // do whatever you want to change here, like: t.setText("Second text to display!"); } }; private final Handler mHandler = new Handler();
install this runnable as a handler, possible in
onCreate()
(but read my advice below):// run the mUpdateUITimerTask's run() method in 10 seconds from now mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);
Advice: be sure you know an Activity
's lifecycle! If you do stuff like that in onCreate()
this will only happen when your Activity
is created the first time! Android will possibly keep your Activity
alive for a longer period of time, even if it's not visible! When a user "starts" it again - and it is still existing - you will not see your first text anymore!
=> Always install handlers in onResume()
and disable them in onPause()
! Otherwise you will get "updates" when your Activity
is not visible at all! In your case, if you want to see your first text again when it is re-activated, you must set it in onResume()
, not onCreate()
!
The first line of new text view is unnecessary
t=new TextView(this);
you can just do this
TextView t = (TextView)findViewById(R.id.TextView01);
as far as a background thread that sleeps here is an example, but I think there is a timer that would be better for this. here is a link to a good example using a timer instead http://android-developers.blogspot.com/2007/11/stitch-in-time.html
Thread thr = new Thread(mTask);
thr.start();
}
Runnable mTask = new Runnable() {
public void run() {
// just sleep for 30 seconds.
try {
Thread.sleep(3000);
runOnUiThread(done);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Runnable done = new Runnable() {
public void run() {
// t.setText("done");
}
};
@user264892
I found that when using a String variable I needed to either prefix with an String of "" or explicitly cast to CharSequence.
So instead of:
String Status = "Asking Server...";
txtStatus.setText(Status);
try:
String Status = "Asking Server...";
txtStatus.setText((CharSequence) Status);
or:
String Status = "Asking Server...";
txtStatus.setText("" + Status);
or, since your string is not dynamic, even better:
txtStatus.setText("AskingServer...");
per your advice, i am using handle and runnables to switch/change the content of the TextView using a "timer". for some reason, when running, the app always skips the second step ("Step Two: fry egg"), and only show the last (third) step ("Step three: serve egg").
TextView t;
private String sText;
private Handler mHandler = new Handler();
private Runnable mWaitRunnable = new Runnable() {
public void run() {
t.setText(sText);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMonster = BitmapFactory.decodeResource(getResources(),
R.drawable.monster1);
t=new TextView(this);
t=(TextView)findViewById(R.id.TextView01);
sText = "Step One: unpack egg";
t.setText(sText);
sText = "Step Two: fry egg";
mHandler.postDelayed(mWaitRunnable, 3000);
sText = "Step three: serve egg";
mHandler.postDelayed(mWaitRunnable, 4000);
...
}
:) Your using the thread in a wrong way. Just do the following:
private void runthread()
{
splashTread = new Thread() {
@Override
public void run() {
try {
synchronized(this){
//wait 5 sec
wait(_splashTime);
}
} catch(InterruptedException e) {}
finally {
//call the handler to set the text
}
}
};
splashTread.start();
}
That's it.
setting the text to sam textview twice is overwritting the first written text. So the second time when we use settext we just append the new string like
textview.append("Step Two: fry egg");
@Zordid @Iambda answer is great, but I found that if I put
mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);
in the run() method and
mHandler.postDelayed(mUpdateUITimerTask, 0);
in the onCreate method make the thing keep updating.
참고URL : https://stackoverflow.com/questions/2300169/how-to-change-text-in-android-textview
'IT story' 카테고리의 다른 글
rc-XYZW 형식의 버전 문자열 순서로 git 태그를 정렬하는 방법은 무엇입니까? (0) | 2020.09.02 |
---|---|
boto3 클라이언트 NoRegionError : 때때로 지역 오류를 지정해야합니다. (0) | 2020.09.02 |
신경망의 가중치를 난수로 초기화해야하는 이유는 무엇입니까? (0) | 2020.09.02 |
Django 1.7에서 마이그레이션을 단순화하는 방법은 무엇입니까? (0) | 2020.09.02 |
Perl에서 해시를 결합하려면 어떻게해야합니까? (0) | 2020.09.02 |