2016-11-10 71 views
4

我试图在textview中显示代码片段。但是我无法在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); 

我创建这个TextView的在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代码段(codesnippet.txt):toHtml。

但它不水平滚动。我该怎么做才能使它像webview水平自动滚动?

输出与上述代码:
enter image description here

后Horizo​​ntalScrollView和code.setHorizo​​ntallyScrolling(真):
enter image description here
水平滚动工作在单line.I细需要显示代码段为一个块。

+0

我不知道如果我这样做是正确的,但也许你没有在你的文本换行? 通常它是\ n但是你是否正在使用Html.fromHtml,那么你应该有
换行符。并使用code.setHorizo​​ntalScrolling,它应该没问题。 –

回答

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> 
+0

我已经尝试过这种方式,但它显示在单行不是多行。此外,我添加tv.setSingleLine(false)后,该问题。但仍显示单行 – erginduran

+0

添加屏幕截图关于此答案 – erginduran