没有 NullPointerException 的 Android 新 ProgressBar?

标签 android progress-bar nullpointerexception

每当我尝试构造 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/

相关文章:

android - ActionBar 宽度中的两个 Spinner 菜单项

android - 如何创建等宽的按钮?

android - 使用Android架构组件LiveData&ViewModel时是否需要使用onSaveInstanceState和onRestoreInstanceState?

android - 如何判断 viewpager 何时完成加载

c# - 为许多方法编写进度条的最佳方法

android - 如何使进度条使用图像而不是在 Android 中使用颜色来显示进度

android - 通知将应用程序置于最前面而无需更改 Activity

java - 什么是NullPointerException,我该如何解决?

java - 为什么我的 View 数组返回 null?

android - 从 ViewPager Activity 访问 fragment 的方法