2016-11-10 20 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

相關問題