我一直在研究一个应用程序,其中一个球(位图)出现在画布上用户点击屏幕的位置。背景是一个xml布局setContentView(R.layout.newsession)。画布是黑色画布。当我设置我的Java父类setContentView(customView),程序工作正常,但是当我将自定义表面视图添加到我的XML布局和setContentView(R.layout.newsession)时,屏幕只显示画布,而OnTouch事件不会没有工作。难道我做错了什么?我已经为此工作了近一个星期,我真的需要帮助。我将发布我的代码以下XML布局和自定义surfaceView。提前致谢!使用OnTouchListener将自定义视图添加到XML布局
XML布局(newsession的)
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/newSessionPage"
>
<ImageView
android:layout_width="231dp"
android:id="@+id/ivStrikeGrid"
android:layout_gravity="center"
android:layout_height="270dp"
android:layout_marginTop="18dp"
android:src="@drawable/strike_grid"
android:layout_marginBottom="10dp"
/>
<appsys.studios.CustomSurfaceViewOne
android:id="@+id/customSurfaceViewOne1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></appsys.studios.CustomSurfaceViewOne
>
</FrameLayout>
自定义SurfaceView
package appsys.studios;
public class CustomSurfaceViewOne extends SurfaceView implements Runnable{
public CustomSurfaceViewOne(Context context, AttributeSet attr) {
super(context, attr);
ourHolder = getHolder();
}
// Other stuff
}
它工作正常,像这样:
newSeshView = new CustomSurfaceViewOne(this, null);
setContentView(newSeshView);
但是,当我尝试从XML使用它没有任何反应布局如下:
newSeshView = new CustomSurfaceViewOne(this, null);
setContentView(R.layout.newsession);
再次感谢! :)
您是否制作了复制粘贴错误?我没有看到任何代码从xml中膨胀自定义视图?如下:'CustomViewOne cvo =(CustomViewOne)findViewById(R.id.customSurfaceViewOne1)' –
对不起,我比较新,而且我不太明白我需要做什么。我应该在我的父java类或我的自定义视图类中做到这一点?我想我可能会忘记这一点,因此无法正常工作。你能否详细说明一下?另外,不要我已经有自定义视图等于? newSeshView = new CustomSurfaceViewOne(this,null); – Jarnuman
那么,在你最后的代码片段中,你说你正在尝试使用xml中的自定义视图。但是,该片段与上面的代码片段相同,并显示了您的视图的程序化实例。如果你正在寻求使用在你的xml文件中声明的视图,你应该从它膨胀你的视图。这意味着在'onCreate()'的某个地方你必须做'setContentView(R.layout.newsession);'然后你可以做CustomViewOne cvo =(CustomViewOne)findViewById(R.id.customSurfaceViewOne1)来获得你的在xml布局文件中声明的自定义视图。 –