Android 开发者参考列出了可用的内置 View 资源中的R.id.progress 。
然而,当我(在我的活动课上)发出声明时:
View pv = getWindow().findViewById(android.R.id.progress);
它返回空值。
即使我将它与ProgressBar
类结合使用,它也会返回 null:
ProgressBar pv = (ProgressBar) getWindow().findViewById(android.R.id.progress);
即使没有 getWindow()它也会返回 null :
ProgressBar pv = (ProgressBar) findViewById(android.R.id.progress);
知道为什么吗?
为了确保我没有产生幻觉,我按照@Geobits 的建议从头开始创建了一个新项目,其中包含下面@ArunGeorge 推荐的博客文章中列出的确切代码:
package com.droidworks;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
public class ProgressBarExampleActivity extends Activity {
private ProgressBar mProgress;
private MyThread mBgThread;
private final Handler mHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mProgress = (ProgressBar) findViewById(android.R.id.progress);
mBgThread = (MyThread) getLastNonConfigurationInstance();
if (mBgThread == null) {
mBgThread = new MyThread();
mBgThread.start();
}
mHandler.post(mThreadWatcher);
}
@Override
public Object onRetainNonConfigurationInstance() {
return mBgThread;
}
@Override
protected void onPause() {
mHandler.removeCallbacks(mThreadWatcher);
super.onPause();
}
private Runnable mThreadWatcher = new Runnable() {
public void run() {
int progress = mBgThread.getProgress();
mProgress.setProgress(progress);
if (progress != 100)
mHandler.postDelayed(this, 50);
}
};
static class MyThread extends Thread {
private int _progress = 0;
public void run() {
for (; _progress < 100; _progress++) {
try {
Thread.sleep(100);
}
catch (InterruptedException ignored) {
}
}
}
private int getProgress() {
return _progress;
}
}
}
果然,这段代码抛出了一个NullPointerException
:
at com.droidworks.ProgressBarExampleActivity$1.run(ProgressBarExampleActivity.java:44)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)