onFling和LinearLayouts

时间:2014-12-07 04:20:17

标签: java android android-linearlayout onfling

我的线性布局:main_linear_layout包含四个线性布局:ll1 ll2 ll3 ll4。每个LinearLayout都包含Buttons。我正在尝试在main_linear_layout上实现onFling方法。我希望能够在Buttons的布局上的任意位置滑动并调用操作。

目前我可以在屏幕上的任何位置滑动,但按钮布局除外。我尝试使用以下代码来解决问题:

swipeLayout = (LinearLayout) findViewById(R.id.main_linear_layout);
//swipeLayout is the main Layout that contains 4 other linear layouts

swipeLayout.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        gestureScanner.onTouchEvent(event);
        return true;
    }
});

但我仍然无法在Buttons的布局上滑动。有谁知道这是为什么?还有其他我需要实现的东西吗?我应该对主线性布局中的每个线性布局实施OnTouchListener吗?或者每个布局中的每个Button

xml中,我在主线性布局中添加了一堆代码:

android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:longClickable="true" 

但这也不起作用。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

如果你有一个LinearLayout,然后有更多的布局,然后按你所说的那样按钮,那么这就按预期运行了。

您只是将监听器添加到外部布局......所以当然,它只会在您滑动时触发。通过在其他布局甚至按钮上滑动,幻灯片事件甚至无法到达该侦听器,因为它已被占用。

您需要将侦听器添加到要检查的每个元素。

执行此操作的一种方法是创建按钮数组并一次完成所有操作:

private Button button1;
private Button button2; 
....
private Button button10;

...
protected void onCreate(Bundle b) {
    super.onCreate(b);
    button1 = findViewById(R.id.button1);
    ...
    button10 = findViewById(R.id.button10);
    OnClickListener onCL = new OnClickListener . . . //do all of your creation here
    Button[] buttons = {button1, button2, . . . , button10};
    for(Button b : buttons) {
        b.setOnClickListener(onCL);
    }
}

答案 1 :(得分:1)

ll1,ll2,ll3,ll4没有接触到触摸事件的原因是因为父线性布局接收到运动事件并且它不会进一步传播。

为什么在主线性布局上需要触摸事件监听器?你想让子布局全部拼凑在一起吗?

如果您希望其他布局在触摸事件上获取,则在触摸侦听器上返回false

swipeLayout.setOnTouchListener(new View.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {

    gestureScanner.onTouchEvent(event);
    return false;
}
});

或者您可以创建4个GestureDetectors并根据按下的视图将事件传递给右侧

swipeLayout.setOnTouchListener(new View.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {

   switch(v.getId()){
    case R.id.ll1:

        gesture1.ontouchEvent(e);
        break;

    case R.id.ll2:

        gesture1.ontouchEvent(e);
        break;
    }
    //etc


    return false;
}
});