【问题标题】:How to display code snippet in textview?如何在文本视图中显示代码片段?
【发布时间】: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 一样水平自动滚动?

使用上述代码输出:

在 Horizo​​ntalScrollView 和 code.setHorizo​​ntallyScrolling(true) 之后:

水平滚动在单行中效果很好。我需要将代码 sn-p 显示为一个块。

【问题讨论】:

  • 我不确定我是否正确,但也许您的文本中没有换行符?通常它是 \n 但是你正在使用 Html.fromHtml 那么你应该有
    换行符。然后使用 code.setHorizo​​ntallyScrolling 应该没问题。

标签: android android-layout textview


【解决方案1】:

您的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>

【讨论】:

  • 我之前已经尝试过了。但它显示为单行而不是多行。我在该问题之后添加了 tv.setSingleLine(false)。但仍然显示单行
  • 添加了关于这个答案的截图
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-22
  • 1970-01-01
  • 2018-03-02
  • 1970-01-01
相关资源
最近更新 更多