我尝试用3个片段在android平台上创建一个应用程序
当我尝试在fragment类中输入一些java代码时,我总是会遇到这样的错误:
java.lang.NullPointerException
例如,使用一个简单的按钮来更改视图:
package com.test;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class creation extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.creation, container, false);
final Button ok = (Button)getView(). findViewById(R.id.button3);
ok.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new mesvideos();
// consider using Java coding conventions (upper char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.layout.creation, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
return root ;
}
或使用VideoView
:
mVideoView = (VideoView) findViewById(R.id.videoView1);
mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() +
"/" + R.raw.presentation));
mVideoView.setMediaController(new MediaController(this));
mVideoView.requestFocus();
答案 0 :(得分:3)
请注明完整的堆栈跟踪,或告诉我们您的代码在哪一行发生NPE,而不是仅仅说您遇到NullPointerException。
FWIW,你的
final Button ok = (Button)getView(). findViewById(R.id.button3);
应该是
final Button ok = (Button) root.findViewById(R.id.button3);
我怀疑因为你刚刚创建了根视图并且还没有返回/设置它,所以getView()将返回null
PS。您的班级名称“创建”是非标准的。 Java类名称应以大写字母开头,如果您的类扩展了Fragment,那么习惯上让类名称以“Fragment”结尾。例如:“CreationFragment”。