[英]Nullpointerexception thrown when trying to findViewById
我有以下活动:
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
在单独的Fragment中,我具有:
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
什么也没有。
尝试在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。
从片段编写代码以初始化按钮,因为您的按钮进入片段布局而不是活动布局。
@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;
}
并从Activity
onCreate
中删除与登录按钮相关的代码。
findViewById()
可以参考根视图。 如果不首先查看,将抛出空指针异常
在任何活动中,您都可以通过调用setContentView(someView);
设置视图setContentView(someView);
。 因此,当您调用findViewById()
,其引用了someView
。 同样,findViewById()仅在该someView
找到ID。 所以在这种情况下,空指针异常
对于片段,适配器,活动...。任何视图的findViewById()
仅会查找id是否在视图中消失,或者,如果您对视图进行膨胀,则还可以使用inflatedView.findViewById()
从该视图中获取视图。 inflatedView
简而言之,请确保您在要引用的布局中包含id
,或者在适当的位置调用findViewById()
(例如adapters getView()
,活动的onCreate()
或onResume()
或onPause()
,片段onCreateView()
, ....)
也有关于UI和后台线程的想法,因为您不能有效地更新bg-threads中的UI
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.