我的项目在 Eclipse 中运行良好,但自从我将我的项目迁移到 AndroidStudio 后,我一直收到这个奇怪的 NullPointerException
,我无法弄清楚它有什么问题。特别是 fragment.getView()
无论出于何种原因总是返回 null
。
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
selectItem(0);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment;
switch(position) {
case 0:
fragment = new Fragment1();
break;
default:
fragment = new Fragment1();
}
switchFragment(fragment, position);
}
private void switchFragment(Fragment fragment, int position){
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.replace(R.id.fragmentContainer, fragment)
.commit();
fragment.getView().setFocusableInTouchMode(true);
}
问题出在 fragment.getView().setFocusableInTouchMode(true)
行。我认为当 FragmentManager
提交 fragment
时,它的 View 应该已经创建,但显然我错了。我试图查找它,但找不到任何令人满意的解释。请帮我解决这个问题。下面是我的 Fragment1
类:
public class Fragment1 extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
return inflater.inflate(R.layout.activity_fragment1, parent, false);
}
}
最佳答案
fragment 交易是异步执行的。把它想象成一个发布到 UI 线程消息队列的可运行对象。
特别是,getView()
将返回您从 onCreateView()
返回的任何内容,但仅在调用生命周期方法之后。在它返回 null 之前。
您应该将诸如 setFocusableInTouchMode()
之类的 View 自定义放入 fragment 本身。 onCreateView()
或 onViewCreated()
是好地方。
与 Android Studio 无关。它在两个 IDE 中的工作方式相同。
关于android - FragmentManager的异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24807630/