让 TextView 自带滚动条

来源:互联网 发布:有手机用windows系统 编辑:程序博客网 时间:2024/04/30 23:17
在android上面让TextView 过多的文字实现有滚动条,之前想简单了以为设置TextView的属性就可以实现,结果还是需要ScrollView配合使用,才能达到滚动条的效果有两种方式实现,

一种是代码写java的layout

Java代码

  1. RelativeLayout.LayoutParams param new RelativeLayout.LayoutParams(80,80);   
  2. //初始化滚动条控件   
  3. ScrollView scrollView =new ScrollView(this);   
  4. scrollView.setScrollContainer(true);   
  5. scrollView.setFocusable(true);   
  6. //初始化文字控件   
  7. TextView textView new TextView(this);   
  8. textView.setHorizontallyScrolling(true);   
  9. textView.setText("走情感路线,哈哈哈,\n 走情感路线,哈哈哈");   
  10.   
  11. scrollView.addView(textView);   
  12. main_view.addView(scrollView, param);  
 

另一种则用layout.xml来实现

 

Xml代码
  1. <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"  
  2.         android:layout_width="fill_parent" android:layout_height="fill_parent"    
  3. android:scrollbars="vertical" android:fadingEdge="vertical">  
  4.         <TextView android:layout_width="fill_parent" android:layout_height="wrap_content"    
  5. android:id="@+id/text_view" android:textColor="#071907" android:paddingTop="5dip" />  
  6. </ScrollView>  

=========================================================================================

一、Xml代码

  1. <TextView  
  2.     android:id="@+id/textview"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:singleLine="false"  
  6.     android:maxLines="5"  
  7.     android:scrollbars="vertical"  
  8.     />

二、还需要在代码中设置 TextView 相应的方法

  1. TextView textView = (TextView)findViewById(R.id.text_view);   
  2. textView.setMovementMethod(ScrollingMovementMethod.getInstance()); 

好了,大功告成。

 

附:

  顺便讲下 TextView 自动滚动的实现方法,下面介绍两种方法:

一、在代码中实现:

     textView .setEllipsize(TextUtils.TruncateAt.MARQUEE);
     textView .setSingleLine(true);
     textView .setMarqueeRepeatLimit(6);

二、在XML中实现:

 <TextView android:id="@+id/TextView01" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:singleLine="true"
  android:text="dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
  android:marqueeRepeatLimit="marquee_forever" android:ellipsize="marquee"
  android:scrollHorizontally="true" android:width="150dip"></TextView>

一切OK,当 textView 获取焦点后,就会自动滚动。

原创粉丝点击