如何将自定义视图插入XML的LinearLayout

时间:2011-05-31 11:14:17

标签: android view android-layout android-xml android-custom-view

所以我有CustomViewView扩展而来。我有一个XML的线性布局。 名为example的XML:

<?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 如何才能使CustomView(此示例中为GameThread)能够插入到xml中?

3 个答案:

答案 0 :(得分:0)

您的行应为:

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

您传递的是布局的ID,而不是您创建的视图的ID。

其余代码看起来很好

答案 1 :(得分:0)

我不知道Jembalang是什么,但我认为你应该删除它。

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

答案 2 :(得分:0)

您说您的布局文件名为“ example.xml ”,但您调用 setContentView(R.layout。 cobagabung 。因此,您的视图是从“ cobagabung.xml ”初始化的。

确保对布局文件名和setContentView调用使用相同的标识符,例如

setContentView(R.layout.example);