【发布时间】:2021-11-23 20:53:33
【问题描述】:
首先,我查看了与此问题相关的所有其他帖子,但没有解决问题。
我试图在片段中显示视频提要,但 findViewById(R.id.videoView) 总是抛出 NullPointException 错误。我相信我已经将问题缩小到 findViewById 返回 null 或 R.id.videoView 为 null(尽管已正确连接到 int)。
CameraView.class:
public class CameraView extends Fragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.cameraview_layout, container, false);
playVideo();
return view;
}
public void playVideo(){
VideoView myVideoView = (VideoView) new AppCompatActivity().findViewById(R.id.videoView);
myVideoView.setVideoURI(Uri.fromFile(new File("C:\\Users\\USER\\Videos\\video.mp4")));
myVideoView.setMediaController(new MediaController(myVideoView.getContext()));
myVideoView.requestFocus();
myVideoView.start();
}
}
cameraview_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
android:gravity="center">
<VideoView
android:id="@+id/videoView"
android:layout_width="342dp"
android:layout_height="288dp"
android:layout_marginTop="149dp"
android:layout_marginBottom="208dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
我不确定为什么 findViewById 仍然返回 null,即使在尝试关注此处和其他地方的许多不同帖子之后也是如此。据我所知, videoView 是一个有效的 ID。任何帮助将不胜感激。
【问题讨论】:
-
new AppCompatActivity()认真的吗? 你不应该自己创建活动实例你应该在onCreateView内部的view上使用findview并将结果存储在片段中的字段中
标签: android android-studio android-fragments video nullpointerexception