【问题标题】:Android new ProgressBar without NullPointerException?没有 NullPointerException 的 Android 新 ProgressBar?
【发布时间】:2011-08-28 15:39:18
【问题描述】:

每当我尝试构建 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;
}

【问题讨论】:

    标签: android progress-bar nullpointerexception


    【解决方案1】:

    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 的默认样式。

    【讨论】:

    • 我发现出了什么问题,我用 new myListAdapter(ArrayListVariable) 而不是正确的 myListAdapter(this.getApplicationContext(),ArrayListVariable) 调用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多