Hacer TextView desplazable en Android
Estoy mostrando texto en un textview que parece ser demasiado largo para caber en una pantalla. Necesito hacer mi TextView desplazable. ¿Cómo puedo hacerlo ¿eso?
Aquí está el código:
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);
24 answers
No es necesario utilizar un ScrollView
en realidad.
Acaba de establecer el
android:scrollbars = "vertical"
Propiedades de su TextView
en el archivo xml de su diseño.
Luego use:
yourTextView.setMovementMethod(new ScrollingMovementMethod());
En su código.
Bingo, se desplaza!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-24 09:31:25
Así es como lo hice puramente en 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>
NOTAS:
android:fillViewport="true"
combinado conandroid:layout_weight="1.0"
hará que textview ocupe todo el espacio disponible.Al definir el Scrollview, NO especifique
android:layout_height="fill_parent"
de lo contrario el scrollview no funciona! (esto me ha hecho perder una hora ahora! FFS).
CONSEJO PROFESIONAL:
Para desplazarse programáticamente hasta la parte inferior después de agregar texto, use esto:
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());
}
});
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 23:27:45
Todo lo que es realmente necesario es el setMovementMethod(). Aquí hay un ejemplo usando un LinearLayout.
File 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>
File 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);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 23:24:36
Haga su textview simplemente agregando esto
TextView textview= (TextView) findViewById(R.id.your_textview_id);
textview.setMovementMethod(new ScrollingMovementMethod());
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-26 02:23:41
No es necesario poner en
android:Maxlines="AN_INTEGER"`
Puedes hacer tu trabajo simplemente agregando:
android:scrollbars = "vertical"
Y, pon este código en tu clase Java:
textview.setMovementMethod(new ScrollingMovementMethod());
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 23:38:51
Usted puede o bien
- rodear el
TextView
por unScrollView
; o - establezca el método de movimiento en
ScrollingMovementMethod.getInstance();
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 23:22:52
La mejor manera que encontré:
Reemplace TextView con un EditText con estos atributos adicionales:
android:background="@null"
android:editable="false"
android:cursorVisible="false"
No hay necesidad de envolver en una vista de desplazamiento.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 23:28:22
Esto es "Cómo aplicar la barra de desplazamiento a tu TextView", usando solo XML.
Primero, necesita tomar un control Textview en el main.xml archivo y escribir algo de texto en él ... así:
<TextView
android:id="@+id/TEXT"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/long_text"/>
A continuación, coloque el control de vista de texto entre la vista de desplazamiento para mostrar la barra de desplazamiento para este texto:
<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>
Eso es todo...
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 23:29:23
Simple. Así es como lo hice:
-
Lado 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>
-
Lado Java:
tv_log = (TextView) findViewById(R.id.tv_log); tv_log.setMovementMethod(new ScrollingMovementMethod());
Bono:
Para que la vista de texto se desplace hacia abajo mientras el texto lo llena, debe agregar:
android:gravity="bottom"
Al archivo xml TextView. Se desplazará hacia abajo automáticamente a medida que entre más texto.
Por supuesto, debe agregar el texto usando la función anexar en lugar de establecer texto:
tv_log.append("\n" + text);
Lo usé para propósitos de Registro.
Espero que esto ayuda ;)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-17 05:35:05
El "consejo pro" anterior de Alguien en algún lugar (Haciendo que TextView se pueda desplazar en Android) funciona muy bien, sin embargo, ¿qué pasa si estás agregando texto dinámicamente a la vista de desplazamiento y te gustaría desplazarte automáticamente hasta la parte inferior después de anexar solo cuando el usuario está en la parte inferior de la vista de desplazamiento? (Tal vez porque si el usuario se ha desplazado hacia arriba para leer algo que no desea restablecer automáticamente a la parte inferior durante un apéndice, lo que sería molesto.)
De todos modos, aquí está is:
if ((mTextStatus.getMeasuredHeight() - mScrollView.getScrollY()) <=
(mScrollView.getHeight() + mTextStatus.getLineHeight())) {
scrollToBottom();
}
El mTextStatus.getLineHeight() hará de modo que usted no scrollToBottom() si el usuario está dentro de una línea desde el final de la ScrollView.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:37
Esto proporcionará un texto de desplazamiento suave con una barra de desplazamiento.
ScrollView scroller = new ScrollView(this);
TextView tv = new TextView(this);
tv.setText(R.string.my_text);
scroller.addView(tv);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-20 12:29:03
Si desea que el texto se desplace dentro de textview, puede seguir lo siguiente:
Primero debería tener que subclase textview.
Y luego usa eso.
A continuación se muestra un ejemplo de una subclase textview.
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;
}
}
Ahora, tienes que usar eso en el XML de esta manera:
<com.yourpackagename.AutoScrollableTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is very very long text to be scrolled"
/>
Eso es todo.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 23:32:18
No encontré el desplazamiento de TextView para soportar el gesto 'fling', donde continúa desplazándose después de un movimiento hacia arriba o hacia abajo. Terminé implementando eso yo mismo porque no quería usar un ScrollView por varias razones, y no parecía haber un método de movimiento que me permitiera seleccionar texto y hacer clic en enlaces.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-30 14:15:04
Agregue lo siguiente en textview en XML.
android:scrollbars="vertical"
Y finalmente, añadir
textView.setMovementMethod(new ScrollingMovementMethod());
En el archivo Java.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 23:34:07
Cuando haya terminado con scrollable, agregue esta línea a la última línea de la vista cuando ingrese algo en la vista:
((ScrollView) findViewById(R.id.TableScroller)).fullScroll(View.FOCUS_DOWN);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 23:30:08
Agregue esto a su diseño 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"
Y en código tienes que escribir las siguientes líneas:
textview.setSelected(true);
textView.setMovementMethod(new ScrollingMovementMethod());
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 23:33:19
Si no desea utilizar la solución EditText, entonces podría tener mejor suerte con:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourLayout);
(TextView)findViewById(R.id.yourTextViewId).setMovementMethod(ArrowKeyMovementMethod.getInstance());
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-27 14:38:29
El siguiente código crea un desplazamiento horizontal automático textview:
Al agregar TextView a xml use
<TextView android:maxLines="1"
android:ellipsize="marquee"
android:scrollHorizontally="true"/>
Establece las siguientes propiedades de TextView en onCreate ()
tv.setSelected(true);
tv.setHorizontallyScrolling(true);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-24 16:54:46
Úsalo así
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:maxLines = "AN_INTEGER"
android:scrollbars = "vertical"
/>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-17 08:05:34
En mi caso.Restricción Layout.AS 2.3.
Implementación de código:
YOUR_TEXTVIEW.setMovementMethod(new ScrollingMovementMethod());
XML:
android:scrollbars="vertical"
android:scrollIndicators="right|end"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-23 11:21:53
Luché con esto durante más de una semana y finalmente descubrí cómo hacer que esto funcione!
Mi problema era que todo se desplazaría como un 'bloque'. El texto en sí estaba desplazándose, pero como un trozo en lugar de línea por línea. Esto obviamente no funcionó para mí, porque cortaría las líneas en la parte inferior. Todas las soluciones anteriores no funcionaron para mí, así que diseñé la mía.
Aquí está la solución más fácil de lejos:
Crear un archivo de clase llamado: 'PerfectScrollableTextView' dentro de un paquete, luego copie y pegue este código en:
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;
}
}
Finalmente cambie su 'TextView' en XML:
De: <TextView
A: <com.your_app_goes_here.PerfectScrollableTextView
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 23:36:32
Ponga maxLines
y scrollbars
dentro de TextView en xml.
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:maxLines="5" // any number of max line here.
/>
Entonces en código java.
textView.setMovementMethod(new ScrollingMovementMethod());
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-13 18:25:21
Tuve este problema cuando estaba usando TextView
dentro de ScrollView
. Esta solución ha funcionado para mí.
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;
}
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-06 01:23:18
Siempre que necesite usar ScrollView como padre, Y también use el método de movimiento de desplazamiento con TextView.
Y cuando vertical a horizontal el dispositivo que el tiempo se producen algún problema. (me gusta) toda la página es desplazable, pero el método de movimiento de desplazamiento no puede funcionar.
Si aún necesita usar ScrollView como método padre o de movimiento de desplazamiento, también use el desc a continuación.
Si no tiene ningún problema, utilice EditText en lugar de TextView
Véase a continuación:
<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"/>
Aquí, el EditText se comporta como TextView
Y su problema se resolverá
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-12 13:28:50