将OnTouchListener设置为自己创建的View

时间:2013-07-09 23:13:51

标签: android canvas view ontouchlistener

我尝试在Android中创建的View上设置OnTouchListener。 我有类,MainActivity,它扩展了Activity和我的drawView,它扩展了View。

我的mainactivity实现了OnTouchListener,我已经实现了drawView。它工作正常,但drawView.setOnTouchListener(MainActivity.this)没有效果。如果我在OnTouchListener中实施drawView并设置DrawView.this.setOnTouchListener(this),则可以正常使用,但必须在我的MainActivity中。

我的MainActivity中的一些代码:

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Display display = getWindowManager().getDefaultDisplay();
drawView = new DrawView(this);
setContentView(R.layout.canvas);
drawView.setOnTouchListener(this);

我的canvas.xml中的一些代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<package.DrawView android:id="@+id/drawView" android:layout_width="fill_parent"       android:layout_height="fill_parent" /> 
</LinearLayout>

有人有想法吗?

祝福 费边

2 个答案:

答案 0 :(得分:0)

看起来您正在创建的DrawView未插入到视图层次结构中。可能你想要的是找到从布局中膨胀的DrawView(而不是创建一个新的)并在那里设置你的OnTouchListener

例如,将最后3行替换为:

setContentView(R.layout.canvas);
DrawView drawView = findViewById(R.id.drawView); // Look up the inflated DrawView
drawView.setOnTouchListener(this);

希望有所帮助!

答案 1 :(得分:0)

我正在开发的游戏遇到同样的问题。

不知道为什么这对我有用。但我将touchListener分配给同一个视图。我假设您在DrawView类上实现了OnTouchlistener(并扩展了View),所以:

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Display display = getWindowManager().getDefaultDisplay();
drawView = new DrawView(this);
drawView.setOnTouchListener(drawView);
setContentView(R.layout.canvas);

所以,在setContentView之前,将setOnTouchListener分配给drawView,再次,我不知道为什么,但这实际上对我有用。希望它有所帮助。