Przewijanie TextView na Androidzie

Wyświetlam tekst w widoku tekstowym, który wydaje się być zbyt długi, aby pasował na jeden ekran. Muszę przewijać Mój widok tekstu. Jak mogę to zrobić to?

Oto kod:

final TextView tv = new TextView(this);
tv.setBackgroundResource(R.drawable.splash);
tv.setTypeface(face);
tv.setTextSize(18);
tv.setTextColor(R.color.BROWN);
tv.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL);
tv.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent e) {
        Random r = new Random();
        int i = r.nextInt(101);
        if (e.getAction() == e.ACTION_DOWN) {
            tv.setText(tips[i]);
            tv.setBackgroundResource(R.drawable.inner);
        }
        return true;
    }
});
setContentView(tv);
Author: Peter Mortensen, 2009-11-17

24 answers

Nie musisz używać ScrollView.

Wystarczy ustawić

android:scrollbars = "vertical"

Właściwości twojego TextView w pliku XML twojego układu.

Następnie użyj:

yourTextView.setMovementMethod(new ScrollingMovementMethod());

W Twoim kodzie.

Bingo, przewija się!
 1453
Author: Amit Chintawar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-24 09:31:25

Tak zrobiłem to czysto w XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ScrollView
        android:id="@+id/SCROLLER_ID"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:fillViewport="true">

        <TextView
            android:id="@+id/TEXT_STATUS_ID"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1.0"/>
    </ScrollView>
</LinearLayout>

Uwagi:

  1. android:fillViewport="true" w połączeniu z android:layout_weight="1.0" spowoduje, że textview zajmie całą dostępną przestrzeń.

  2. Podczas definiowania widoku przewijania nie określaj android:layout_height="fill_parent" w przeciwnym razie widok przewijania nie działa! (to spowodowało, że zmarnowałem właśnie godzinę! FFS).

PRO TIP:

Aby programowo przewijać do dołu po dodaniu tekstu, użyj tego:

mTextStatus = (TextView) findViewById(R.id.TEXT_STATUS_ID);
mScrollView = (ScrollView) findViewById(R.id.SCROLLER_ID);

private void scrollToBottom()
{
    mScrollView.post(new Runnable()
    {
        public void run()
        {
            mScrollView.smoothScrollTo(0, mTextStatus.getBottom());
        }
    });
}
 276
Author: Someone Somewhere,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-28 23:27:45

Wszystko, co jest naprawdę potrzebne, to setMovementMethod (). Oto przykład użycia LinearLayout.

Plik main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:id="@+id/tv1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="@string/hello"
    />
</LinearLayout>

Plik WordExtractTest.java

public class WordExtractTest extends Activity {

    TextView tv1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv1 = (TextView)findViewById(R.id.tv1);

        loadDoc();
    }

    private void loadDoc() {

        String s = "";

        for(int x=0; x<=100; x++) {
            s += "Line: " + String.valueOf(x) + "\n";
        }

        tv1.setMovementMethod(new ScrollingMovementMethod());

        tv1.setText(s);
    }
}
 117
Author: EddieB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-28 23:24:36

Make your textview just adding this

TextView textview= (TextView) findViewById(R.id.your_textview_id);
textview.setMovementMethod(new ScrollingMovementMethod());
 44
Author: matasoy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-26 02:23:41

Nie jest konieczne Wkładanie

android:Maxlines="AN_INTEGER"`

Możesz wykonać swoją pracę po prostu dodając:

android:scrollbars = "vertical"

I umieść ten kod w swojej klasie Javy:

textview.setMovementMethod(new ScrollingMovementMethod());
 36
Author: Ahsan Raza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-28 23:38:51

Możesz albo

  1. otoczyć {[0] } przez ScrollView; lub
  2. ustawić metodę ruchu na ScrollingMovementMethod.getInstance();.
 27
Author: Samuh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-28 23:22:52

The best way I found:

Zamień TextView na EditText z tymi dodatkowymi atrybutami:

android:background="@null"
android:editable="false"
android:cursorVisible="false"

Nie ma potrzeby owijania w widoku przewijania.

 17
Author: Valentin Galea,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-28 23:28:22

To jest "jak zastosować pasek przewijania do widoku tekstowego", używając tylko XML.

Najpierw musisz przejąć kontrolę Textview w main.plik xml i zapisać do niego tekst ... TAK:

<TextView
    android:id="@+id/TEXT"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="@string/long_text"/>

Następnie umieść kontrolkę widoku tekstowego pomiędzy widokiem przewijania, aby wyświetlić pasek przewijania dla tego tekstu:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent">

    <ScrollView
        android:id="@+id/ScrollView01"
        android:layout_height="150px"
        android:layout_width="fill_parent">

        <TextView
            android:id="@+id/TEXT"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="@string/long_text"/>

    </ScrollView>
</RelativeLayout>
To wszystko...
 13
Author: mOmO,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-28 23:29:23

Proste. Tak to zrobiłem:

  1. Strona XML:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 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"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        tools:context="com.mbh.usbcom.MainActivity">
        <TextView
            android:id="@+id/tv_log"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="vertical"
            android:text="Log:" />
    </RelativeLayout>
    
  2. Strona Javy:

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

Bonus:

Aby widok tekstu przewijał się w dół, gdy tekst go wypełniał, musisz dodać:

    android:gravity="bottom"

Do pliku XML TextView. Przewija się automatycznie w dół, gdy pojawi się więcej tekstu.

Oczywiście należy dodać tekst za pomocą funkcji append zamiast ustawionego tekstu:

    tv_log.append("\n" + text);

Użyłem go do celów logowania.

Mam nadzieję, że to pomaga;)

 12
Author: MBH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-17 05:35:05

The" Pro tip " powyżej od kogoś gdzieś ( Dokonywanie TextView scrollable na Androida ) działa świetnie, jednak, co jeśli dynamicznie dodajesz tekst do ScrollView i chcesz automatycznie przewijać do dołu po dodaniu tylko, gdy użytkownik jest na dole ScrollView? (Być może dlatego, że jeśli użytkownik przewija się w górę, aby przeczytać coś, czego nie chcesz automatycznie resetować na dole podczas dodawania, co byłoby denerwujące.)

Anyway, here it jest:

if ((mTextStatus.getMeasuredHeight() - mScrollView.getScrollY()) <=
        (mScrollView.getHeight() + mTextStatus.getLineHeight())) {
    scrollToBottom();
}

MTextStatus.getLineHeight() sprawi, że nie będziesz scrollToBottom (), jeśli użytkownik znajduje się w jednej linii od końca widoku przewijania.

 11
Author: Mark Cramer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 10:31:37

Zapewni to płynne przewijanie tekstu za pomocą paska przewijania.

ScrollView scroller = new ScrollView(this);
TextView tv = new TextView(this);
tv.setText(R.string.my_text);
scroller.addView(tv);
 9
Author: IT-Dan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-20 12:29:03

Jeśli chcesz, aby tekst był przewijany w widoku tekstowym, możesz wykonać następujące czynności:

Najpierw należy podklasować textview.

A potem użyj tego.

Poniżej znajduje się przykład podklasowanego widoku tekstu.

public class AutoScrollableTextView extends TextView {

    public AutoScrollableTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setEllipsize(TruncateAt.MARQUEE);
        setMarqueeRepeatLimit(-1);
        setSingleLine();
        setHorizontallyScrolling(true);
    }

    public AutoScrollableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setEllipsize(TruncateAt.MARQUEE);
        setMarqueeRepeatLimit(-1);
        setSingleLine();
        setHorizontallyScrolling(true);
    }

    public AutoScrollableTextView(Context context) {
        super(context);
        setEllipsize(TruncateAt.MARQUEE);
        setMarqueeRepeatLimit(-1);
        setSingleLine();
        setHorizontallyScrolling(true);
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if(focused)
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean focused) {
        if(focused)
            super.onWindowFocusChanged(focused);
    }

    @Override
    public boolean isFocused() {
        return true;
    }
}

Teraz musisz użyć tego w XML w ten sposób:

 <com.yourpackagename.AutoScrollableTextView
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="This is very very long text to be scrolled"
 />
To wszystko.
 8
Author: Dipendra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-28 23:32:18

Nie znalazłem przewijania TextView, aby obsługiwać gest "fling", gdzie kontynuuje przewijanie po przesunięciu w górę lub w dół. Sam to wdrożyłem, bo z różnych powodów nie chciałem korzystać z widoku przewijania, a nie było ruchu, który pozwalał mi na zaznaczanie tekstu i klikanie w linki.

 6
Author: android.weasel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-30 14:15:04

Dodaj następujący tekst w widoku XML.

android:scrollbars="vertical"

I na koniec dodaj

textView.setMovementMethod(new ScrollingMovementMethod());

W pliku Java.

 5
Author: user3921740,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-28 23:34:07

Kiedy skończysz z przewijaniem, dodaj tę linię do ostatniego wiersza widoku, gdy wprowadzisz cokolwiek w widoku:

((ScrollView) findViewById(R.id.TableScroller)).fullScroll(View.FOCUS_DOWN);
 4
Author: Rahul Baradia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-28 23:30:08

Dodaj to do układu XML:

android:ellipsize="marquee"
android:focusable="false"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="To Make An textView Scrollable Inside The TextView Using Marquee"

I w kodzie musisz napisać następujące linijki:

textview.setSelected(true);
textView.setMovementMethod(new ScrollingMovementMethod());
 4
Author: Ritesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-28 23:33:19

Jeśli nie chcesz korzystać z rozwiązania EditText, możesz mieć więcej szczęścia:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.yourLayout);
    (TextView)findViewById(R.id.yourTextViewId).setMovementMethod(ArrowKeyMovementMethod.getInstance());
}
 3
Author: Justin Buser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-27 14:38:29

Poniższy kod tworzy automatyczne przewijanie tekstu w poziomie:

Podczas dodawania TextView do XML użyj

<TextView android:maxLines="1" 
          android:ellipsize="marquee"
          android:scrollHorizontally="true"/>

Ustaw następujące właściwości TextView w OnCreate ()

tv.setSelected(true);
tv.setHorizontallyScrolling(true); 
 2
Author: whitepearl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-24 16:54:46

Użyj go w ten sposób

<TextView  
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:maxLines = "AN_INTEGER"
    android:scrollbars = "vertical"
/>
 1
Author: Kamil Ibadov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-17 08:05:34

W moim przypadku.Ograniczenie Layout.AS 2.3.

Implementacja kodu:

YOUR_TEXTVIEW.setMovementMethod(new ScrollingMovementMethod());

XML:

android:scrollbars="vertical"
android:scrollIndicators="right|end"
 0
Author: Sasha 888,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-23 11:21:53

Zmagałem się z tym przez ponad tydzień i w końcu wymyśliłem, jak to zrobić!

Moim problemem było to, że wszystko będzie przewijać jako "blok". Sam tekst był przewijany, ale jako fragment, a nie linia po linii. To oczywiście nie działało dla mnie, ponieważ odcinało linie na dole. Wszystkie poprzednie rozwiązania nie działały dla mnie, więc stworzyłem własne.

Oto najprostsze rozwiązanie:

Stwórz plik klasy o nazwie: 'PerfectScrollableTextView' wewnątrz pakietu, następnie skopiuj i wklej ten kod w:

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;

public class PerfectScrollableTextView extends TextView {

    public PerfectScrollableTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    public PerfectScrollableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    public PerfectScrollableTextView(Context context) {
        super(context);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if(focused)
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean focused) {
        if(focused)
            super.onWindowFocusChanged(focused);
    }

    @Override
    public boolean isFocused() {
        return true;
    }
}

Na koniec Zmień swój 'TextView' w XML:

From: <TextView

Do: <com.your_app_goes_here.PerfectScrollableTextView

 0
Author: Petro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-28 23:36:32

Umieść maxLines i scrollbars wewnątrz TextView w xml.

<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:maxLines="5" // any number of max line here.
    />

Następnie w kodzie java.

textView.setMovementMethod(new ScrollingMovementMethod());

 0
Author: Khemraj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-13 18:25:21

Miałem ten problem, gdy używałem TextView wewnątrz ScrollView. To rozwiązanie zadziałało dla mnie.

scrollView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                description.getParent().requestDisallowInterceptTouchEvent(false);

                return false;
            }
        });

        description.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                description.getParent().requestDisallowInterceptTouchEvent(true);

                return false;
            }
        });
 0
Author: Rohit Mandiwal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-06 01:23:18

Gdy potrzebujesz użyć ScrollView jako rodzica , a także użyć metody Ruchu Przewijania z TextView.

I kiedy pionowo do poziomego urządzenia, że czas wystąpić jakiś problem . (jak) cała strona jest przewijalna, ale metoda Ruchu Przewijania nie może działać.

Jeśli nadal musisz użyć ScrollView jako metody nadrzędnej lub przewijania, użyj również poniższego desc.

Jeśli nie masz żadnych problemów To używasz EditText zamiast TextView

Patrz poniżej:

<EditText
     android:id="@+id/description_text_question"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:background="@null"
     android:editable="false"
     android:cursorVisible="false"
     android:maxLines="6"/>

Tutaj EditText zachowuje się jak TextView

I twój problem zostanie rozwiązany

 0
Author: D Prince,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-12 13:28:50