【问题标题】:How to pass a keyEvent object to a Button to let it appears like clicked?如何将 keyEvent 对象传递给 Button 以使其看起来像被点击?
【发布时间】:2010-09-26 13:53:26
【问题描述】:

我已经制作了一个 SurfaceView 来接受 OnTouchEvent,在这个视图中,我使用 Button.draw(Canvas) 手动绘制了一个 Button(而不是创建 ViewGroup)。

现在,这个按钮可以在我的SurfaceView上绘制,但是当我将一个keyEvent从OnTouchEvent传递给Button时,比如Button.onTouchEvent(keyEvent),但是这个按钮不能显示点击效果

所以问题是我如何将 keyEvent 手动传递给 View 并显示它在布局中显示的内容????

有什么想法吗?谢谢!!

【问题讨论】:

  • 如果你看到我的源代码,你会注意到,通过调用setPressed(true),按钮获得了点击效果。然后经过一小段延迟后关闭setPressed(false)。您需要将其编码到您的实现中。

标签: android surfaceview


【解决方案1】:

我确信有更好的方法可以做到这一点……但我想不通。所以这就是我想出的。

我创建了自己的 Button 扩展。并在我的xmls 中创建MyButton 的组件。

<com.stackoverflow.android.example.MyButton android:text="@+id/Button01" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></com.stackoverflow.android.example.MyButton>

您需要将Button 的每个实例更改为com.stackoverflow.android.example.MyButton

package com.stackoverflow.android.example;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.widget.Button;

public class MyButton extends Button {

    final int MSG_MYBUTTON_HIGHLIGHT_ON = 0;
    final int MSG_MYBUTTON_HIGHLIGHT_OFF = 1;

    public MyButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    Handler mHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case MSG_MYBUTTON_HIGHLIGHT_ON:
                setPressed(true);
                sendEmptyMessageDelayed(MSG_MYBUTTON_HIGHLIGHT_OFF, ViewConfiguration.getPressedStateDuration());
                break;
            case MSG_MYBUTTON_HIGHLIGHT_OFF:
                setPressed(false);
            default:
                break;
            }
        };
    };

    public void performVirtualClick()
    {
        mHandler.sendEmptyMessage(MSG_MYBUTTON_HIGHLIGHT_ON);
        performClick();

    }

}

调用performVirtualClick 函数...就可以了。

【讨论】:

    猜你喜欢
    • 2016-04-30
    • 2011-09-27
    • 2011-03-13
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多