0

Hello I am really new on android development and I would like to ask a simple question.

I have a button (buttonR2C1). When I click the buttonR2C1 I change the text of my textView (the textview is included inside a scrollView).The problem is that the position of the scrollView remains the same.

I would like to add an action that brings my ScrollView in position 0,0 by using the scrollTo action.

Can anyone help me achieve this?

.java

    final TextView tv2 = (TextView) findViewById(R.id.mainL1R2);
    final Button button1 = (Button) findViewById(R.id.buttonR2C1);
    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            tv2.setText(getResources().getString(R.string.L1R2C1));
        }
    });

.xml

        <Button
            android:id="@+id/buttonR2C1"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Capitolo 1"
            android:textSize="18sp" />

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/mainL1R2"
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:fontFamily="CustomText"
                android:gravity="left"
                android:scrollHorizontally="true"
                android:text="@string/L1R2C1"
                android:textSize="20sp"
                android:textStyle="normal" />
Adrian Heine
  • 4,051
  • 2
  • 30
  • 43
  • I tried to add tv2.post(new Runnable() { @Override public void run() { tv2.scrollTo(0,0); } }); but nothing happens.. – user3210337 Jan 18 '14 at 17:16
  • 1
    What's your problem exactly, it seems like you already know what to do? – fweigl Jan 18 '14 at 17:18
  • Finally I figured out by myself. on .java file I add final ScrollView sv2 = (ScrollView) findViewById(R.id.scrollView1); and this inside the onClick sv2.post(new Runnable() { @Override public void run() { sv2.scrollTo(0,0); } }); and it works as a charm!! Hope that would help others too. – user3210337 Jan 18 '14 at 17:36
  • thanks Ascorbin for your response...seems like it works that way ;) – user3210337 Jan 18 '14 at 17:37

1 Answers1

2

You have to use the scrollTo method of the ScrollView, not the TextView, like

   final ScrollView scr = (ScrollView) findViewById(R.id.scrollView1);
   scr.scrollTo(x, y); 

To scroll exactly to your TextView, you'll have to get the position of the TextView.

Have a look at this answer.

Community
  • 1
  • 1
fweigl
  • 21,278
  • 20
  • 114
  • 205