2016-11-24 82 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