android:seekbar.setprogress()给出nullpointer异常

v1l68za4  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(448)

这个问题在这里已经有答案了

什么是nullpointerexception,如何修复它(12个答案)
四年前关门了。
我用过 seekbar 喜欢很多次,但从来没有遇到过问题。昨天我在处理我不太熟悉但成功实现的片段。但在一天结束的时候,当我把seekbar加入到片段中,问题就开始了。我不确定这是因为碎片还是什么。这是我的密码。
fragment\u main.xml文件

<LinearLayout>
<SeekBar
    android:id="@+id/seek"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:max="100"/>
</LinearLayout>

fragmentmain.java文件

public class FragmentMain extends Fragment {

final static String TAG = "FragmentMain";
TextView mainTextView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);

    SeekBar seekBar = (SeekBar) getActivity().findViewById(R.id.seek);
    seekBar.setProgress(40);

    return view;
}
}

这个fragmenmain是我的viewpager的中心页面。
我不知道为什么我的代码会崩溃 NullPointerExceptionsetProgress .
随时建议编辑。

iovurdzv

iovurdzv1#

改变

SeekBar seekBar = (SeekBar) getActivity().findViewById(R.id.seek);

SeekBar seekBar = (SeekBar) view.findViewById(R.id.seek);
ryevplcw

ryevplcw2#

问题就在这里

SeekBar seekBar = (SeekBar) getActivity().findViewById(R.id.seek);

您需要找到父视图中的视图,而不是上下文中的视图,将其替换为

SeekBar seekBar = (SeekBar) view.findViewById(R.id.seek);

希望有帮助

相关问题