0

我一直在使用一些不错的教程来在我的 android 上绘制图形。我还想添加在这里找到的很酷的手势演示:

http://developer.android.com/resources/articles/gestures.html

这需要这些代码行:

GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
gestures.addOnGesturePerformedListener(this); 

这很好,但我意识到在我的演示中我正在尝试使用“在 Android 中使用图形”中的代码进行构建。演示很有意义,一切都很有意义,但我通过使用发现:

setContentView(new Panel(this));

按照 Playing With Graphics 教程的要求,findViewById 似乎不再有效并返回 null。起初我正要发布一个关于为什么会发生这种情况的更愚蠢的问题,对 setContentView 的快速测试让我意识到 findViewById 返回 null 的原因,我只是不知道如何解决这个问题。我在这里缺少的关键是什么?我意识到新的面板正在做一些参考,但我不确定如何在这里建立联系。

R.id.gestures 在 main.xml 中被定义为:(就像教程一样)

<android.gesture.GestureOverlayView
    android:id="@+id/gestures"
    android:layout_width="fill_parent" 
    android:layout_height="0dip"
    android:layout_weight="1.0" />

所以我确实确认了

setContentView(new Panel(this))

导致问题。所以我知道问题是我必须弄清楚如何以某种方式将 android.gesture.GestureOverlayView 添加到面板类中,我只是不知道该怎么做。

在与此作斗争之后,我通常知道我现在需要做什么,该怎么做。我想我需要在 main.xml 中创建一个面板,或者弄清楚如何在 main.xml 中为代码中的手势构建什么。我很接近,因为我这样做了: GestureOverlayView gestures = new GestureOverlayView(this);

这让我现在有了一个非空手势,不幸的是,因为我没有告诉它在任何我认为它没有真正出现的地方填充 Parent,所以我正在努力找出布局参数。我什至走在正确的轨道上吗?

4

2 回答 2

0

In order for findViewById to work it needs to know which layout file the context is using. That's what setContentView is for. Since you defined the layout in main.xml, you'll need to call

setContentView(R.layout.main);

(instead of any other call to setContentView) to tell the activity that that's the layout it's supposed to use. Once you do that, findViewById will know where to look for the View with ID "gestures".

于 2011-07-19T17:38:13.560 回答
0

我自己一直在研究一些示例代码,还没有真正写出任何有意义的东西,但也许很简单,系统找不到视图,因为你设置了一个不同的视图?

大多数示例在 setContentView 中都有对资源的引用(例如setContentView(R.id.gestures)),不是吗?因此,后来找不到该视图也就不足为奇了。...除非我在这一点上完全是新手...

于 2010-04-27T23:18:37.573 回答