A类: -
ProgressBar progressBar;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);}
B级: -
new Thread(new Runnable() {
int i = 0;
int progressStatus = 0;
public void run() {
while (progressStatus < 100) {
progressStatus += doWork();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
((Activity) cnt).runOnUiThread(new Runnable() {
public void run() {
XMPPClient xc = new XMPPClient();
xc.progressBar = new ProgressBar(cnt);
xc.progressBar.setProgress(progressStatus);
// Toast.makeText(cnt, "ok", Toast.LENGTH_SHORT).show();
i++;
}
});
}
}
private int doWork() {
return i * 3;
}
}).start();
when i added this line :- xc.progressBar = new ProgressBar(cnt);
then i did not get nullpointerexception. But now my progress bar is **not updating.**
请任何人帮助我。
答案 0 :(得分:4)
ProgressBar progressBar;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
ClassB classb = new ClassB(this, progressBar);
}
public class ClassB{
private Context cnt;
private ProgressBar progressBar;
public ClassB(Context context, ProgressBar pBar){
cnt = context;
progressBar = pBar;
}
}
现在你可以使用progressBar而不是像以前的代码那样创建一个新的! 只是一个快速概述...
答案 1 :(得分:0)
: -
ProgressBar progressBar;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
////Then Use the Reference on Progressbar
ClassB classb = new ClassB(this, progressBar);
}
然后在ClassB中: -
public class ClassB{
private Context cnt;
private ProgressBar progressBar;
public ClassB(Context context, ProgressBar pBar){
cnt = context;
progressBar = pBar;
new Thread(new Runnable() {
int i = 0;
int progressStatus = 0;
public void run() {
while (progressStatus < 100) {
progressStatus += doWork();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
((Activity) cnt).runOnUiThread(new Runnable() {
public void run() {
XMPPClient xc = new XMPPClient();
xc.progressBar = new ProgressBar(cnt);
xc.progressBar.setProgress(progressStatus);
// Toast.makeText(cnt, "ok", Toast.LENGTH_SHORT).show();
i++;
}
});
}
}
private int doWork() {
return i * 3;
}
}).start();
}