尝试findViewById时抛出Nullpointerexception

我有以下活动:

public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new StartFragment()) .commit(); } Button login = (Button) findViewById(R.id.loginButton); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(MainActivity.this,LoginActivity.class); startActivity(intent); } }); } 

当我尝试为R.id.loginButton调用findViewByID时,我得到一个NPE,我猜这是因为loginButton在一个单独的片段中,我有:

 public static class StartFragment extends Fragment { public StartFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_main, container, false); } } 

但是,我不确定如何解决这个问题,以便找到loginButton ID。 我之前没有使用过片段,所以我意识到我可能正在使用它们/错误地实现它们。 fragment_main包含LinearLayout中的几个按钮,而activity_main只包含一个FrameLayout

编写代码来从片段初始化按钮,因为你的按钮是片段布局而不是活动的布局。

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); Button login = (Button) rootView.findViewById(R.id.loginButton); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(MainActivity.this, LoginActivity.class); startActivity(intent); } }); return rootView; } 

并从onCreate of Activity删除与登录按钮相关的代码。

尝试在Fragment实现你的onCreateView(...)

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); View something = rootView.findViewById(R.id.something); something.setOnClickListener(new View.OnClickListener() { ... }); return rootView; } 

Button位于片段布局( fragment_main.xml )中,而不在活动布局( activity_main.xml )中。 生命周期中的onCreate()太早,无法在活动视图层次结构中找到它,并返回null 。 在null上调用方法会导致NPE。

findViewById()适用于对根视图的引用。 如果没有视图,则会抛出空指针exception

在任何活动中,您都可以通过调用setContentView(someView);设置视图setContentView(someView); 。 因此,当您调用findViewById() ,它会引用someView 。 另外findViewById()只有在someView才能找到id。 所以在你的情况下空指针exception

对于片段,适配器,活动,….任何视图的findViewById()只会在视图中查找id exixts如果你正在给视图充气,那么你也可以使用inflatedView.findViewById()从中获取视图inflatedView

简而言之,请确保您所指的布局中有id ,或者在适当的位置调用findViewById() (例如,适配器getView() ,活动的onCreate()onResume()onPause() ,片段onCreateView() , ….)

还有一个关于UI和后台线程的想法,因为你无法在bg-threads中有效地更新UI