Android新的ProgressBar如何避免空指针异常?

3
每当我尝试构建一个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;
}
1个回答

0

空指针异常是由于您传递给构造函数的空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时覆盖默认样式。


我找到了问题所在,我调用它时使用的是new myListAdapter(ArrayListVariable),而不是正确的myListAdapter(this.getApplicationContext(),ArrayListVariable)。 - anonymous

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接