如何在外部触摸事件中隐藏Recyclerview?

时间:2016-10-10 14:05:21

标签: android view

我有view,当我点击按钮/布局时我想显示它,当我触摸其他地方时隐藏它。我该怎么做? 我在dispatchTouchEvent(Motion Event)中编写了一些代码并且它正在运行。但是,我认为必须有另一种方法来实现它。

1 个答案:

答案 0 :(得分:0)

您可以使用另一个可单击的视图填充RecyclerView的外部,并为该视图实现setOnTouchListener方法。这是一个例子:

假设我们在RelativeLayout的顶部有RecyclerView:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:focusable="true">

<android.support.v7.widget.RecyclerView 
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:scrollbars="vertical" />

    <!--View below is just to fill the remaining space. We will use this view to catch outside touch-->

<View 
    android:id="@+id/outside_detector"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/recyclerView"
    android:clickable="true"
    android:focusable="true"/>
</RelativeLayout>

当我们点击RecyclerView外面时,我们想隐藏并显示我们的Recyclerview:

((View) findViewById(R.id.outside_detector)).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                if(arg1.getAction() == MotionEvent.ACTION_DOWN){
                    if(recyclerView.getVisibility() == View.VISIBLE){
                        recyclerView.setVisibility(View.INVISIBLE);
                    }else{
                        recyclerView.setVisibility(View.VISIBLE);
                    }
                }
                return true;
            }
        });

如果要在按钮单击时显示recyclerview,则只需在按钮ClickListener中写入recyclerView.setVisibility(View.VISIBLE)方法!

希望这有帮助!