2016-10-10 83 views
1

我有一个view,我想在点击按钮/布局时显示它,并在我触摸其他位置时隐藏它。我该怎么做? 我在dispatchTouchEvent(Motion Event)中写了一些代码,它正在工作。但是,我认为必须有另一种方式来做到这一点。如何在外部触摸事件中隐藏recyclerview?

+0

你用“RecyclerView查看”是什么意思?你的意思是recyclerView的一个项目吗? – Umarov

+0

这意味着RecyclerView里面的视图,在这种情况下,我认为 –

回答

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)方法!

希望这会有所帮助!

+0

thaks并不重要,但是如果我在这个'RelativeLayout'中有很多视图,为了更容易的拦截事件创建一个'view',是否正确? –

+0

对不起,我没有明白。你介意澄清你说的话吗? – Umarov

+0

我认为创建'view'可能会有一些副作用 –