2016-01-04 33 views
0

我想通過表格佈局來檢查按鈕的條件,然後用setText來改變它們。 我遇到的問題是,我得到ClassCastException。 我看到它說我無法將按鈕投射到ViewGroup,但我不知道爲什麼會發生這種情況,我不想在此時改變任何內容。 我相信這條線(69)是問題所在,但肯定爲什麼。AppCompatButton不能轉換爲android.view.ViewGroup

View view = ((ViewGroup) ((ViewGroup) tableLayoutChild).getChildAt(i));

代碼:

public Button aiPlayerPick() { 
     Button btn = null; 
     TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout); 

     for (int rowIndex = 0; rowIndex < tableLayout.getChildCount(); rowIndex++) { 
      View tableLayoutChild = tableLayout.getChildAt(rowIndex); 
      if (tableLayoutChild instanceof TableRow) { 
       for (int i = 0; i < ((ViewGroup) tableLayoutChild).getChildCount(); i++) { 
        View view = ((ViewGroup) ((ViewGroup) tableLayoutChild).getChildAt(i)); 
        if (view instanceof Button && view.getTag() == aiPickedButton) { 

         View btn_v = view.findViewWithTag(aiPickedButton); 
         System.out.println("Button: " + btn_v); 
         //btn = (Button) findViewById(R.id.btn_v); 

         break; 
        } else { 
         i++; 
        } 
       } 
      } 
     } 
     return btn; 
    } 

錯誤:

Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatButton cannot be cast to android.view.ViewGroup 
    at com.example.richardcurteis.connect3.MainActivity.aiPlayerPick(MainActivity.java:69) 
    at com.example.richardcurteis.connect3.MainActivity.playerClick(MainActivity.java:49) 
    at com.example.richardcurteis.connect3.MainActivity.humanPlayerTurn(MainActivity.java:34) 
    at com.example.richardcurteis.connect3.MainActivity.receiveClick(MainActivity.java:29) 
    at java.lang.reflect.Method.invoke(Native Method)  
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270) 

回答

1

即使你存儲View類型的變量,使用CAST (ViewGroup)強制投是之前發生存儲。您正在拍攝TableRow的子項並將其投射到ViewGroup,但其父母實際上是View,因此失敗。

你不需要秒施法,因爲getChildAt()回報View

View view = ((ViewGroup) tableLayoutChild).getChildAt(i); 
+0

完美。隊友的歡呼聲 –

相關問題