动作事件在Android中捕获

时间:2012-02-17 14:01:01

标签: android

我已为应用程序编写代码。

应用程序布局是这样的。

0 1 2 3 4

5 6 7 8 9

现在,当用户触摸一个键(用户将手指放在按钮上,如5)时,其文本应在文本框中输入为“5 down”。但是当用户释放密钥时,文本应设置为“5 up”。但是在完成密钥发布之前,如果用户用手指在布局上滑动到6,则应检测到它并且文本应设置为“向下6”。它应该像那样继续,但是当用户释放密钥时,文本应设置为“向上当前触摸的密钥”。我已经使用了MOTION_UP,MOTION_DOWN,MOTION_MOVE的东西,但我没有得到如何完成它。请在这个问题上为我提供一些启示。发生的事情是,当我从5下滑到6时,事件仍处于“向下5”但是当我取下手指然后它设置为“向上5”。但我希望滑动方法能够完成。所以请告诉我如何做到这一点。

这是我的代码

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // select_btn = (Button) findViewById(R.id.ok);
    // home_btn = (Button) findViewById(R.id.home);
    et = (EditText) findViewById(R.id.entry);
    et.setText("", TextView.BufferType.EDITABLE);
    b = new Bundle();


    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    for (int i = 0; i < mybtn.length; i++) {
        String btnid = "btn" + i;
        int resid = getResources().getIdentifier(btnid, "id",
                getPackageName());
        mybtn[i] = (Button) findViewById(resid);
        mybtn[i].setOnTouchListener(this);

    }



}


@Override
public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    String s = null;
    s = ((Button) v).getText().toString().trim();
    switch (event.getAction()) {
    // case MotionEvent.ACTION_MOVE:
    // Do some stuff
    // et.setText("move android"+s, TextView.BufferType.EDITABLE );
    // break;

    case MotionEvent.ACTION_DOWN:
        et.setText("down android" + s, TextView.BufferType.EDITABLE);
        // Do some stuff
        break;
    case MotionEvent.ACTION_UP:
        et.setText("up android" + s, TextView.BufferType.EDITABLE);

    }
    return true;
}

1 个答案:

答案 0 :(得分:0)

我没有测试它,但我想它应该可行:

private int currentSelected = 0;

@Override
public boolean onTouch(View v, MotionEvent event)
{
    String s = null;

    s = ((Button) v).getText().toString().trim();

    switch (event.getAction())
    {

        case MotionEvent.ACTION_DOWN:

            currentSelected = Integer.valueOf(s);
            et.setText("down android" + s, TextView.BufferType.EDITABLE);
            break;

        case MotionEvent.ACTION_UP:
            et.setText("up android" + currentSelected, TextView.BufferType.EDITABLE);
            break;

        case MotionEvent.ACTION_MOVE:
            if (Integer.valueOf(s) != currentSelected)
            {
              et.setText("down android" + s, TextView.BufferType.EDITABLE);
              currentSelected = Integer.valueOf(s);
            }
            break;

    }
    return true;
}