I am displaying text in a textview that appears to be too long to fit into one screen. I need to make my TextView scrollable. How can I do that?
Here is the code:
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);
You can either
TextView
by aScrollView
; orScrollingMovementMethod.getInstance();
.All that is really necessary is the setMovementMethod(). Here's an example using a LinearLayout.
File main.xml
File WordExtractTest.java
You don't need to use a
ScrollView
actually.Just set the
properties of your
TextView
in your layout's xml file.Then use:
yourTextView.setMovementMethod(new ScrollingMovementMethod());
in your code.
Bingo, it scrolls!
This is how I did it purely in XML:
NOTES:
android:fillViewport="true"
combined withandroid:layout_weight="1.0"
will make the textview take up all available space.When defining the Scrollview, DO NOT specify
android:layout_height="fill_parent"
otherwise the scrollview doesn't work! (this has caused me to waste an hour just now! FFS).PRO TIP:
To programmatically scroll to the bottom after appending text, use this:
Simple. This is how I did it:
XML Side:
Java side:
Bonus:
To let the text view scroll down as the text fill it, you have to add:
to the TextView xml file. It will scroll down automatically as more text comes in.
Of course you need to add the text using the append function instead of set text:
I used it for Log purpose.
I hope this helps ;)
I didn't find TextView scrolling to support the 'fling' gesture, where it continues scrolling after a flick up or down. I ended up implementing that myself because I didn't want to use a ScrollView for various reasons, and there didn't seem to be a MovementMethod that both allowed me to select text and click on links.