How can I set attribute onClick to a ScrollView?

2019-05-27 11:19发布

问题:

I have the following layout

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white" >

<LinearLayout
    android:id="@+id/answerMainFrame"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:isScrollContainer="true"
    android:onClick="toQuestion" >

    <ImageView
        android:id="@+id/answer_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:contentDescription="@string/question_img_cd" />

    <TextView
        android:id="@+id/answer"
        style="@style/Question" />
</LinearLayout>

Sometimes the ScrollView is too small and won't fill the whole screen but still I want to call the method toQuestion() clicking anywhere on the screen.

I've tried setting android:layout_height="wrap_content" to the LinearLayout and android:onClick="toQuestion" to the ScrollView but same result.

回答1:

You could try to let the LinearLayout implement the onClick attribute and then set:

android:fillViewport="true"

to the ScrollView.



回答2:

I had a similar issue, and simply got rid of the scrollview itself. Instead, I directly inserted the TextView itself, with the constraints previously put on the ScrollView. The whole purpose of my ScrollView was to scroll in the TextView, not among several items, so it seemed a more elegant way to do.

Add a (vertical) scrollbar to my textview in activity.hmtl :

    <TextView
    android:id="@+id/tvInfo"
    (...) 
    android:scrollbars="vertical" 
    />

Add this to the onCreate method:

    oTV = (TextView) findViewById(R.id.tvInfo);
    oTV.setMovementMethod(new ScrollingMovementMethod());

No need to write the scrolling response. I like that.

I found the solution here (thx Juned Mughal) :

http://www.android-examples.com/make-textview-scrollable-in-android-programmatically/



回答3:

To make the scroll view fill the screen change:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white" >

to

<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:layout_weight="1"
android:background="@android:color/white" >

and for the click put this in your onCreate method:

((ScrollView) findViewById(R.id.scrollView))
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        toQuestion();
                    }
                });