【问题标题】:onFling and LinearLayoutsonFling 和 LinearLayouts
【发布时间】:2014-12-07 04:20:16
【问题描述】:

我的线性布局:main_linear_layout 包含四个线性布局:ll1ll2ll3ll4。每个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" 

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

【问题讨论】:

    标签: java android android-linearlayout onfling


    【解决方案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);
        }
    }
    

    【讨论】:

    • 如果我在四个布局中有 20 个按钮,有没有办法可以让一个监听器影响整个布局,或者我需要重复相同的代码 20 次?
    • @user2456977 查看我的回复 - 我添加了一种~简单的方法来做到这一点。只需创建一个数组,然后查看按钮。
    • 我还没有机会检查答案。一旦我检查,我会选择一个答案
    【解决方案2】:

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

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

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

    swipeLayout.setOnTouchListener(new View.OnTouchListener() {
    
    @Override
    public boolean onTouch(View v, MotionEvent event) {
    
        gestureScanner.onTouchEvent(event);
        return false;
    }
    });
    

    或者您可以创建 4 个 GestureDetector 并根据按下的视图将事件传递给正确的事件

    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;
    }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      相关资源
      最近更新 更多