如何在textview中显示代码片段?

erg*_*ran 5 android textview android-layout

我正在尝试在textview中显示代码片段。但是我无法使长文本行在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);
Run Code Online (Sandbox Code Playgroud)

我在fragment.fragment_layout.xml中创建此textview:

<?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>
Run Code Online (Sandbox Code Playgroud)

我正在coordinatorlayout> nestedscrollview> linearlayout(fragment container)中的活动中开始此片段

每个人的宽度大小是“匹配父母”

这是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);
}
Run Code Online (Sandbox Code Playgroud)

我从vim:toHtml获得了该代码段(codesnippet.txt)。

但是它不能水平滚动。如何使它像webview一样水平自动滚动?

使用上面的代码输出:
在此处输入图片说明

在Horizo​​ntalScrollView和code.setHorizo​​ntallyScrolling(true)之后:
在此处输入图片说明
水平滚动在单行中效果很好,我需要将代码段显示为一个块。

ple*_*eft 0

您的TextView内容应该如下HorizontalScrollView所示:

<HorizontalScrollView 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">

    <TextView android:layout_width="40dp"
        android:layout_height="wrap_content"
        android:scrollHorizontally="true"
        android:text="Horizontal scroll view"/>

</HorizontalScrollView>
Run Code Online (Sandbox Code Playgroud)