最近學習Android中,試着實現一個簡單的顯示新聞Demo的時候,遇到了一個問題:一條新聞的內容文字很多,放在TextView上面超出屏幕了,怎么破?
查了一下資料,找到了兩種方法實現:
1. 只用TextView,用TextView自帶的滾動條完成全部展示,在布局xml文件中,TextView的屬性需要設置android:scrollbars和android:singleLine,如下:
<TextView
android:id="@+id/news_item_content_text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:lineSpacingExtra="2dp" android:scrollbars="vertical" android:singleLine="false" android:text="this is content, blablabla..." android:textColor="@color/news_content_color" />
主要是黃色的;然后在Activity的onCreate或者FragMent的onViewCreated方法中添加代碼如下:
TextView contentTV = (TextView) view.findViewById(R.id.news_item_content_text_view);
contentTV.setMovementMethod(ScrollingMovementMethod.getInstance());
到這里就基本OK了,不過因為在我的Demo中,是在一個Activity中顯示了兩個Fragment,左邊的是新聞列表,右邊展示新聞詳情,然后出現了一個問題:顯示了一個比較長的新聞,然后把新聞內容拖到最后,在切換新聞條目后,展示新聞內容的TextView無內容顯示,需要觸摸一下TextView區域才能顯示,處理辦法:
在每次切換新聞后,都在TextView的setText方法后面添加一個TextView的滾動條滾動的方法,如下:
TextView contentTV = (TextView) view.findViewById(R.id.news_item_content_text_view);
contentTV.setText(content);
contentTV.scrollTo(0, 0);//滾動條滾動到0位置
這樣子就OK了。
2. 布局的時候把TextView放在一個ScrollView里面,這樣子就更簡單了,不需要任何代碼處理。
<ScrollView android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> <TextView android:id="@+id/news_item_content_text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:lineSpacingExtra="2dp" android:text="this is content, blablabla..." android:textColor="@color/news_content_color" /> </ScrollView>
當TextView文字內容很長的時候,ScrollView自動會顯示滾動條,不需要我們再去寫代碼實現了。