简体   繁体   English

在Android中,如何在ScrollView中检测Click和LongClick

[英]In Android, how to detect Click and LongClick in ScrollView

I have very simple activity: just TextView inside ScrollView. 我有一个非常简单的活动:ScrollView中只有TextView。

I want to handle user clicks and longclicks on whole ScrollView to start some action. 我想处理整个ScrollView上的用户单击和longclick,以启动一些操作。 I can easily handle click events on TextView, but cannot on ScrollView. 我可以轻松处理TextView上的单击事件,但不能处理ScrollView上的单击事件。

When text content is long enough it's not a problem, but when it's just one line of text than user needs to click that particular line (top of the screen) which is not very usefull. 当文本内容足够长时,这不是问题,但是当仅一行文本时,用户需要单击该特定行(屏幕顶部),这不是很有用。

How to detect click events in ScrollView? 如何在ScrollView中检测单击事件? (or any other solution) (或任何其他解决方案)

Sample activity: 样本活动:

public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
}

public void testOnClick(View view) {
    Log.d("TestActivity", "Hello? Anybody there?");
    finish();
}}

And layout: 和布局:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff0000"
    android:clickable="true"
    android:onClick="testOnClick">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="test text\n test text\n test text" />
</ScrollView>

As mentioned in this post you should set clickable false to the other elements within the scroll view for it to work OnClickListener on scrollView 如本文所述,您应将滚动视图中的其他元素设置为clickable false,以使其在scrollView上运行OnClickListener

Cheers 干杯

What you want is to having a bigger click target for your TextView . 您想要为TextView设置更大的点击目标。

Just set the click / long click listener on the TextView . 只需在TextView上设置click / long click侦听器。 You can add a padding to increase the size of the view like this: 您可以添加填充以增加视图的大小,如下所示:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"
    android:text="test text\n test text\n test text" />

This ensures a click target of at least 40dp, depending on your font size, which is easy to click on. 这样可以确保至少40dp的点击目标,具体取决于您的字体大小,易于点击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM