我正在显示文本的TextView,似乎太长,以适合
在一个屏幕上。我需要使我的TextView可滚动。我该怎么办
了吗?
代码如下:
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);
所有真正需要的是setMovementMethod()。下面是一个使用LinearLayout的例子。
文件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>
文件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);
}
}
如果你想在textview中滚动文本,那么你可以遵循以下步骤:
首先,你应该子类textview。
然后用它。
下面是一个子类化的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;
}
}
现在,你必须在XML中这样使用它:
<com.yourpackagename.AutoScrollableTextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is very very long text to be scrolled"
/>
就是这样。