0

因此,我有一個CustomViewView擴展。我有一個來自XML的線性佈局。 命名爲example的XML:如何將自定義視圖插入XML的LinearLayout

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res/jembalang.comfest.game" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <jembalang.compfest.game.GameThread 
    android:id="@+id/game_view" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    </jembalang.compfest.game.GameThread> 
    <Button 
    android:text="Button" 
    android:id="@+id/button1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"> 
    </Button> 
</LinearLayout> 

而且使用XML

setContentView(R.layout.cobagabung); 
gameView = (GameThread) Jembalang.this.findViewById(R.id.game_view); 
gameView.setFocusable(true); 
gameView.setFocusableInTouchMode(
gameView.start(); 

的代碼我增加了GameThread構造,如果這是幫助

public class GameThread extends View implements Runnable,OnKeyListener{ 
    public GameThread(Context context,AttributeSet attr){ 
     super(context, attr); 
     ... 
    } 
    public GameThread(Context context) { 
     super(context); 
     ... 
    } 

我覺得有什麼不對我的路這樣做,因爲findViewById返回null 我應該怎麼做,使我的CustomViewGameThread在這個例子)能夠插入到XML?

+0

你實際使用完整的包? – Kakey 2011-05-31 11:18:45

+1

使用合併標籤而不是頂級的線性佈局 – vnshetty 2011-05-31 11:24:14

+0

@Jinda恩,恩,我看着http://developer.android.com/resources/samples/ApiDemos/res/layout/custom_view_1.html,它給出了完整的包。 – dieend 2011-05-31 11:32:02

回答

0

你行應爲:

gameView = (GameThread) Jembalang.this.findViewById(R.id.game_view); 

您傳遞佈局的ID,而不是您所創建的視圖。

你的代碼的其餘部分看起來不錯

+0

啊,對不起,我輸錯了它,它實際上就像你寫的。 ,gameView仍然爲空::( – dieend 2011-05-31 11:29:29

+0

爲什麼你必須完全限定你的這個指針,才能調用Jembalang.this.findViewById調用?你是否在你添加視圖的同一個對象上進行調用? – fleetway76 2011-05-31 11:51:07

+0

gameView實現可運行,我需要啓動它,這就是爲什麼我需要再次調用它 – dieend 2011-05-31 12:21:02

0

我不知道是什麼Jembalang是,但我認爲你應該刪除。

gameView = (GameThread) findViewById(R.id.game_view); 
0

你說你的佈局文件被稱爲 「的example.xml」,但你叫的setContentView(R.layout。cobagabung。因此,您的視圖從「cobagabung.xml」初始化。

請確保您使用的佈局文件名和調用的setContentView相同的標識符,如

setContentView(R.layout.example); 
相關問題