每当我尝试构造 ProgressBar 时,它都会给出 NullPointerException。网上的例子说第二个参数可以为null,即使它应该是AttributeSet?这可能是问题的一部分吗?这是为 Android 1.5 编译的。
public class myListAdapter implements ListAdapter {
...
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(TAG,"getView");
LinearLayout view = new LinearLayout(context);
//This new ProgressBar causes N.P.E.:
ProgressBar p = new ProgressBar(context, null,android.R.attr.progressBarStyleSmall); ;
view.addView(p);
return view;
}
最佳答案
NPE 是由您传递给构造函数的空 AttributeSet 参数引起的。
您可以尝试使用不同的构造函数,并使用主题设计您的控件:
ProgressBar p = new ProgressBar( new ContextThemeWrapper( context, R.style.MyTheme );
然后在res/values/themes.xml中定义一个主题:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyTheme" parent="@android:style/Theme">
<item name="android:progressBarStyle">@android:style/Widget.ProgressBar.Small</item>
</style>
</resources>
这基本上是在应用 MyTheme 时覆盖 ProgressBar 的默认样式。
关于没有 NullPointerException 的 Android 新 ProgressBar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6055206/