为了方便查看,已使用markdown编辑形成新博文。
本文Mardown地址
最近做应用的时候有用到TextView单行长文本,当文本内容过长时候又想实现触摸水平滑动效果。网上找了很多,都没有看到有效解决方案。
其中,最常见的也是最笨拙滴采用重写TextView并继承实现touch 和 Gesture手势。
后来经提醒发现了其实最简单的方案:
直接使用 EditText 就好了。因为edittext需要编辑和移动光标的缘故,使得它是可以水平滑动的。因此我们只需要设置其为透明背景,并且不可以获得焦点。
android:focusable="false"
<span style="background-color: rgb(240, 240, 240);"><span style="font-size:10px;">android:background="@android:color/transparent"</span></span>
(注:不能使用editable=“false”,因为这样就不能编辑滑动。而通过使用focusable="false"同样不可编辑同时可以滑动)
补充一点,要隐藏光标,只用设置
android:cursorVisible="false"//隐藏
或
setCursorVisible(false);
这里记录下来给大家点儿启示。不必用自以为聪明的方法办最笨的事儿。共勉。
<EditText android:id="@+id/tt" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_weight="1" android:layout_margin="15dip" android:background="@android:color/transparent" android:focusable="false" android:singleLine="true" android:text="简易实现 TextView单行文本水平触摸滑动效果。简易实现 TextView单行文本水平触摸滑动效果。简易实现 TextView单行文本水平触摸滑动效果" android:textColor="#000" android:textSize="20dip" /> </LinearLayout>效果图:
源码地址(附长文本折叠展开)
后边贴一些小白教程,可以忽视:(以下内容非原创,见谅)
一、只想让TextView显示一行,但是文字超过TextView的长度怎么办?
在开头显示省略号
android:singleLine="true"
android:ellipsize="start"
在结尾显示省略号
android:singleLine="true"
android:ellipsize="end"
在中间显示省略号
android:singleLine="true"
android:ellipsize="middle"
横向自动滚动(跑马灯效果)
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true"
以上4个效果都要加上 android:singleLine="true",因为TextView默认是会自动换行的
android:ellipsize是设置文字过长时,该怎么显示
android:marqueeRepeatLimit="marquee_forever"是设置永远重复,当然你也可以设置具体的数字
android:focusable="true"和android:focusableInTouchMode="true"一定要加上,不然滚动效果出不来
二、怎么让TextView可以垂直滚动?
在Java代码中加入下面一句话就可以实现垂直滚动
textView.setMovementMethod(ScrollingMovementMethod.getInstance());