简体   繁体   English

同一片段中的ListView和自定义SurfaceView

[英]ListView and custom SurfaceView in same fragment

I'm writing a custom SurfaceView implementation: 我正在编写一个自定义的SurfaceView实现:

CustomSurfaceView.java : CustomSurfaceView.java

public class CustomSurfaceView extends SurfaceView {
  private void init() { }

  // ...
}

I want to call CustomSurfaceView from a fragment, myFragment . 我想打电话给CustomSurfaceView从一个片段, myFragment Every example I can find on the web does this by 我可以在网上找到的每个示例都是通过

class myFragment extends Fragment {
  // ...

  public View onCreateView() {
    return new CustomSurfaceView(getActivity());
  }
}

The problem with this approach is that I also have a ListView, myList , in myFragment . 这种方法的问题是,我也有一个ListView, myList ,在myFragment It works like this: 它是这样的:

my_fragment.xml : my_fragment.xml

<LinearLayout>
  <ListView id="@+id/my_list"/>
  <SurfaceView id="@+id/custom_surface_view"/>
</LinearLayout>

myFragment.java : myFragment.java

class myFragment extends Fragment {
  // ...

  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.my_fragment, container, false);

    myList = (ListView) view.findViewById(R.id.my_list);

    return view;
  }
}

That configuration, without the CustomSurfaceView , works fine. 没有CustomSurfaceView配置可以正常工作。

Then, I tried adding after myList = ... : 然后,我尝试在myList = ...之后添加:

customSurfaceView = (CustomSurfaceView) view.findViewById(R.id.custom_surface_view);

which results in an Unexpected cast to CustomSurfaceView: layout tag was SurfaceView . 这导致Unexpected cast to CustomSurfaceView: layout tag was SurfaceViewUnexpected cast to CustomSurfaceView: layout tag was SurfaceView

If in my xml layout file I change <SurfaceView/> to <com.example.CustomSurfaceView/> , I get a crash on runtime ( Binary XML : Error inflating class com.example.CustomSurfaceView ). 如果在我的xml布局文件中将<SurfaceView/>更改为<com.example.CustomSurfaceView/><com.example.CustomSurfaceView/>在运行时崩溃( Binary XML : Error inflating class com.example.CustomSurfaceView )。

So my question is this: what am I doing wrong, and which is the proper, working way to include both a ListView and CustomSurfaceView in the same myFragment ? 所以我的问题是:我在做错什么,以及将ListViewCustomSurfaceView在同一myFragment的正确的工作方式是什么?

The problem was that I hadn't defined by constructors to the proper specification. 问题是我没有由构造函数定义正确的规范。

Adding this code to CustomSurfaceView.java removed the error inflating crash: 将此代码添加到CustomSurfaceView.java消除导致崩溃的error inflating

public CustomSurfaceView(Context context, AttributeSet attrs) {
  super(context, attrs);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM