我在另一个线程中使用setText,即子线程.但对于以下代码,它给出了错误
只有创建视图层次结构的原始线程才能触及其视图.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img = (ImageView)findViewById(R.id.img);
pb = (ProgressBar)findViewById(R.id.pb);
this.tv = (TextView)findViewById(R.id.perc);
tv.setText("30 %");
pb.setProgress(30);
pb.setMax(100);
}
public void set(int p)
{
tv.setText(p + " %");
}
protected void onStart()
{
super.onStart();
pb.setProgress(20);
Thread t = new Thread(new Runnable()
{
@Override
public void run()
{
try {
int i = pb.getProgress();
while(i <100)
{
while(pb.getProgress()<100)
{
pb.incrementProgressBy(5);
Thread.sleep(1000);
}
i+=10;
pb.setProgress(i);
Thread.interrupted();
set(i);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
});
t.start();
}
Run Code Online (Sandbox Code Playgroud)
Bon*_*dax 53
您需要对该textview的引用然后执行:
textView.post(new Runnable() {
public void run() {
textView.setText(yourText);
}
});
Run Code Online (Sandbox Code Playgroud)
Moh*_*ikh 11
使用runOnUiThread用于更新UI控件.在你的情况下:
runningActivity.runOnUiThread(new Runnable() {
public void run() {
tv.setText(p + " %");
}
});
Run Code Online (Sandbox Code Playgroud)
编辑:
Activity mActivity;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mActivity= this;
...
..//The rest of the code
} //close oncreate()
thread{
mActivity.runOnUiThread(new Runnable() {
public void run() {
tv.setText(p + " %");
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41335 次 |
| 最近记录: |