【发布时间】:2017-03-24 12:23:43
【问题描述】:
我正在尝试在 textview 中显示代码 sn-p。但我无法使长文本行在 textview 中自动水平滚动。
代码:
TextView code = new TextView(getActivity());
TableRow.LayoutParams paramsExample = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,TableRow.LayoutParams.WRAP_CONTENT);
code.setBackgroundColor(getResources().getColor(android.R.color.black));
code.setPadding(5, 5, 5, 5);
code.setTextColor(getResources().getColor(android.R.color.white));
code.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
code.setClickable(true);
code.setLayoutParams(paramsExample);
setCode(code, R.raw.codesnippet);
ll.addView(code);
我在 fragment.fragment_layout.xml 中创建这个文本视图:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment_ll"
android:orientation="vertical">
</LinearLayout>
我在一个活动中开始这个片段 coordinatorlayout > nestedscrollview > linearlayout(片段容器)
每个人的宽度大小都是“匹配父项”
这是setcode方法:
public void setCode(TextView tv, int rawId) {
Resources res = getResources();
BufferedReader input = new BufferedReader(new InputStreamReader(
res.openRawResource(rawId)));
StringBuffer sb = new StringBuffer();
try {
String line;
while ((line = input.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Spanned spannedCode = Html.fromHtml(sb.toString());
tv.setText(spannedCode);
}
我从 vim:toHtml 得到那个代码 sn-p (codesn-p.txt)。
但它不会水平滚动。我应该怎么做才能让它像 webview 一样水平自动滚动?
在 HorizontalScrollView 和 code.setHorizontallyScrolling(true) 之后:
水平滚动在单行中效果很好。我需要将代码 sn-p 显示为一个块。
【问题讨论】:
-
我不确定我是否正确,但也许您的文本中没有换行符?通常它是 \n 但是你正在使用 Html.fromHtml 那么你应该有
换行符。然后使用 code.setHorizontallyScrolling 应该没问题。
标签: android android-layout textview