在Fragment中设置SurfaceView

时间:2013-11-12 20:48:19

标签: android android-fragments

怎么了家伙,我有一个非常愚蠢的问题,但我真的无法想出这一个。我正在尝试设置一个视图来扩展SurfaceView的片段。这是托管活动的onCreate方法:

public class ProbeMainActivity extends FragmentActivity{

BattleSurfaceView BSView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    BSView = new BattleSurfaceView(this);
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    BattleFragment fragment = new BattleFragment();
    fragmentTransaction.add(BSView.getId(), fragment);
    fragmentTransaction.commit();

}

}

这是片段:

public class BattleFragment extends Fragment implements OnTouchListener
{   
/* Surface View for this activity */
BattleSurfaceView BSView;
DummySpell sp;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    /* instantiating the surface view */
    BSView = new BattleSurfaceView(this.getActivity());
    /* setting the listener - this, because it is defined within the activity */
    BSView.setOnTouchListener(this);

}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return this.BSView;
}
    ...

}

每次,我都会收到“没有查看”的例外情况。我错过了什么? 非常感谢,希望你能解决这个问题。干杯

1 个答案:

答案 0 :(得分:2)

如果您只想在片段中显示自定义SurfaceView('MySurfaceView'),那么只需执行以下操作:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return new BattleSurfaceView(getActivity());
    }