强制onTouchEvent的RelativeLayout焦点

时间:2015-09-25 14:37:57

标签: android touch android-relativelayout

我正在开发我的第一款游戏。机制很简单:在屏幕上随机移动的流行气泡。我的画布是Activity的RelativeLayout。布局很简单。

<RelativeLayout
    android:id="@+id/frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/header" />

触摸事件是通过onTouch实施View.OnTouchListener方法定义的。课程摘录如下:

public class BubbleActivity extends AppCompatActivity implements View.OnTouchListener {
    private RelativeLayout mFrame;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        //...
    }       
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //...
        setContentView(R.layout.activity_bubble);
        mFrame = (RelativeLayout) findViewById(R.id.frame);
        //...
    }       
    @Override
    protected void onResume() {
        super.onResume();
        mFrame.setOnTouchListener(this);
    }
}

问题是有时触摸事件不会发生。我想知道是否有某种机制可以始终抓住焦点,确保我的RelativeLayout对象中的触摸事件。

欢迎任何帮助

1 个答案:

答案 0 :(得分:0)

如果您希望TouchEvent抓住所有RelativeLayout,请实施自定义视图展开RelativeLayout并处理onInterceptTouchEvent()中的事件。

示例:

public class RelativeLayoutExt extends RelativeLayout {
    public RelativeLayoutExt(Context context) {
        super(context);
    }

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

    public RelativeLayoutExt(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public RelativeLayoutExt(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        // TODO handle your touches here
        return super.onInterceptTouchEvent(ev);
    }
}