2017-07-27 98 views
0

在我的Android应用我有2个布局使用viewFlipper的Android viewFlipper导致NullPointerException异常

<?xml version="1.0" encoding="utf-8"?> 
    <ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android" 
     android:orientation="vertical" android:layout_width="match_parent" 
     android:id="@+id/switching" 
     android:layout_height="match_parent"> 

      <include layout="@layout/activity_login"/> 
      <include layout="@layout/content_team_choose"/> 
      <include layout="@layout/waiting"/> 
    </ViewFlipper> 

<?xml version="1.0" encoding="utf-8"?> 
<ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:id="@+id/switch_game" 
    android:layout_height="match_parent"> 

    <include layout="@layout/main_game"/> 
    <include layout="@layout/chat"/> 
</ViewFlipper> 
在我的拳头活动

创建有机会获得这样的

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.switching); 
     viewFlipper = (ViewFlipper) findViewById(R.id.switching); 

//some other code which triggers the change of the view, 
//like a onClickListener 

        viewFlipper.setDisplayedChild(1); 
视图

,这工作正常。在我的第二个活动中,如果我尝试访问另一个视图鳍状肢,并且我执行vievFlipper.setDisplayedChild(1)将引发NullPointerExcption。所以我试了

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.switch_game); 
    viewFlipper = (ViewFlipper) findViewById(R.id.switch_game); 
    if(viewFipper == null) 
     Log.d("ViewError", "the viewFlipper is null"); 

和日志出现,但我不明白为什么只有在这种情况下视图为空。 我甚至尝试在第二个活动中获得布局“切换”,这也给了我相同的问题。

编辑。 NullPointerException由viewFlipper.setDisplayedChild(1)引发; 试图访问布局的孩子,但我不知道,如果只有儿童是空或全部viewFlipper,所以我tryied代码的最后部分,验证整个布局为null

+0

请检查的setContentView布局是正确的R.layout.main_game – Meenal

+0

我还没有注意到的第一和第二码之间的矛盾,但我已经tryied替代“R.layout.main_game “与”R.layout.switch_game“);”并没有什么能伪装的 – DeNasti

回答

2

当应用程序尝试使用具有空值的对象引用时,引发NullPointerException。

一个ViewFlipper主要用在情况下,当我们需要一个视图转换为另一种。

viewFlipper = (ViewFlipper) findViewById(R.id.switch_game); 
+1

是的,对不起,我在最后一部分中有点混淆。 NullPointerException引发尝试访问布局的子项,但我不确定是否只有儿童是null或所有viewFlipper,所以我尝试了代码的最后一部分,验证整个布局为空 – DeNasti

相关问题