【问题标题】:How to insert custom view into XML's LinearLayout如何将自定义视图插入 XML 的 LinearLayout
【发布时间】:2011-05-31 11:14:16
【问题描述】:

所以我有一个从View 扩展而来的CustomView。我有一个来自 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中?

【问题讨论】:

  • 你真的在使用完整的包吗?
  • 在顶层使用合并标签而不是线性布局
  • @Jinda 嗯,是的,我在看developer.android.com/resources/samples/ApiDemos/res/layout/…,它提供了完整的包。
  • @vnshetty 不,它仍然没有工作:(
  • @dieend 对不起,我无法找到你失踪的地方。你最好用断点调试你的代码。当你的 setContentView 被执行时,你的自定义视图应该被初始化......

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


【解决方案1】:

你的行应该是:

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

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

你的代码的其余部分看起来不错

【讨论】:

  • 啊,对不起。我打错了。其实和你写的一样。但是不,gameView 仍然是 null。:(
  • 为什么你必须完全限定你的 this 指针才能调用 Jembalang.this.findViewById?您是在调用添加视图的同一个对象吗?
  • gameView实现了Runnable,我需要启动它,所以我需要再次调用它
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    setContentView(R.layout.example);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 2015-10-30
      • 2014-09-02
      • 2012-08-27
      • 1970-01-01
      • 2021-10-21
      • 2023-04-02
      相关资源
      最近更新 更多