2016-11-24 70 views
0

如何將片段添加到基礎SurfaceView?我得到的異常將片段添加到基礎SurfaceView

java.lang.IllegalArgumentException: No view found for id 0x7f0b0050 

我認爲這是由於在沒有的setContentView設置任何佈局,如

setContentView(R.layout.activity_main); 

,而不是我設置爲自定義surfaceview參考...

final GameSurface gs = new GameSurface(this); 
setContentView(gs); 

然後在surfaceview回調ontouch(...) - 如果用戶點擊表面上的片段應該加載

@Override 
public boolean onTouchEvent(MotionEvent event) { 

..... 

     FragmentManager fragmentManager =((Activity)context).getFragmentManager(); 
     FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
     ExchangeFragment fragment = new ExchangeFragment(); 
     fragmentTransaction.add(R.id.relLayout, fragment); 
     fragmentTransaction.commit(); 

在此先感謝

編輯:

沒有崩潰任何時間較長,但片段不會顯示出來。爲什麼? 感謝@Kelevandos,並在另一組線程

How to inflate one view with a layout

這就是答案,我向哈得AttributSet添加到自定義surfaceViews構造。

缺什麼?下面是XML文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
> 


    <se.brickgame.brickbreaker.GameSurface 

     android:id="@+id/surfaceId" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
    /> 

    <RelativeLayout 

     android:id="@+id/relLayout" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
    > 
    </RelativeLayout> 

編輯2:

我也已將此添加到代碼

fragmentManager.executePendingTransactions(); 
System.out.println("FRAGMENT ISADDED = " + fragment.isAdded()); 
System.out.println("FRAGMENT VISIBLE = " + fragment.isVisible()); 
System.out.println("FRAGMENT HIDDEN = " + fragment.isHidden()); 
System.out.println("FRAGMENT ISINLAYOUT = " + fragment.isInLayout()); 

,得到了下面的輸出

11-25 16:09:07.957 12155-12155/se.brickgame.brickbreaker ISystem.out: FRAGMENT ISADDED = true 
11-25 16:09:07.957 12155-12155/se.brickgame.brickbreaker I/System.out: FRAGMENT VISIBLE = true 
11-25 16:09:07.957 12155-12155/se.brickgame.brickbreaker I/System.out: FRAGMENT HIDDEN = false 
11-25 16:09:07.957 12155-12155/se.brickgame.brickbreaker I/System.out: FRAGMENT ISINLAYOUT = false 

所以......它似乎在那裏不是在佈局 - 如何解釋?

回答

1

問題是您的GameSurface沒有內部視圖,其編號爲R.id.relLayout。片段事務必須被賦予一個你想放置片段的容器。

一個解決方案是爲Activity創建佈局,像這樣:

<RelativeLayout> 
    <GameSurface/> 
    <RelativeLayout/> //This is the Fragment container 
</RelativeLayout> 

將它設置爲Activity的內容佈局和檢索GameSurface這樣的:

​​37

這實際上應該在Android中處理佈局和視圖的方式,所以如果您重新設計您的解決方案,最好是這樣。

如果由於某種原因您不能/不想要,您將不得不重新考慮用另一種方法替換Fragment部件,該方法不需要Fragment

+0

謝謝,但片段不會出現。我現在無法弄清楚,請參閱編輯。 – java

+0

這個答案幫了我很多 – java