进度条setProgress()

时间:2018-09-12 20:41:56

标签: android

我试图在一个片段中设置进度条的值,但应用程序因以下错误而崩溃:

  

试图在空对象引用上调用虚拟方法'void android.widget.ProgressBar.setProgress(int)'

这是我的代码:

@BindView(R.id.progressBar1)
ProgressBar progressBar1;   
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    progressBar1.setProgress(90);
    return inflater.inflate(R.layout.fragment_tab_overview, container, false);
}

以及XML文件中的进度栏​​:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".modinfosection.TabOverviewFragment">
<ProgressBar
    android:id="@+id/progressBar1"
    style="@android:style/Widget.ProgressBar.Small.Inverse"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:indeterminate="true"
    android:layout_centerInParent="true"
    android:padding="30dp"
    android:clickable="false"/>
<ImageView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:src="@drawable/googleg_standard_color_18"
    android:clickable="false"/>
</RelativeLayout>

我在这里想念东西吗?

3 个答案:

答案 0 :(得分:1)

您正在尝试在放大视图之前设置进度条的进度,因此进度条尚不存在。

尝试在inflate调用之后设置进度,或在onFinishInflate方法中进行设置

答案 1 :(得分:1)

问题是您在扩大布局或绑定视图之前试图获取该progressView。只需稍微改变一下通话顺序即可:

@BindView(R.id.progressBar1)
ProgressBar progressBar1;   
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Your inflate call should always happen first thing in this method.
    // Then you can modify the view as you please
    View view = inflater.inflate(R.layout.fragment_tab_overview,
                                 container,
                                 false);

    // Since you're using ButterKnife, you need to actually trigger it to
    // process your annotation and bind your view.  Otherwise, it will
    // still be null.
    ButterKnife.bind(this, view);

    // Now you can safely access the progress bar!
    progressBar1.setProgress(90);

    // Be sure to return your inflated root view
    return view;
}

答案 2 :(得分:1)

使用黄油刀时,请使用ButterKnife.bind(this, view);,以将布局小部件与活动/片段绑定。