我一直在研究一個應用程序,其中一個球(位圖)出現在畫布上用戶點擊屏幕的位置。背景是一個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佈局文件中聲明的自定義視圖。 –