我目前的问题如下:我有一个RecyclerView,这个RecyclerView的每个元素都有一个TextView。我希望TextView自动滚动。如果到目前为止尝试了怎么办:
自定义TextView:
public class ScrollCustomTextView extends AppCompatTextView {
public ScrollCustomTextView(Context context) {
super(context);
}
public ScrollCustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context,attrs,defStyle);
}
public ScrollCustomTextView(Context context, AttributeSet attrs) {
super(context,attrs);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (focused)
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
@Override
public void onWindowFocusChanged(boolean focused) {
if(focused)
super.onWindowFocusChanged(focused);
}
@Override
public boolean isFocused() {
return true;
}
}
和我的.xml文件如下所示:
<package.ScrollCustomTextView
android:id="@+id/main_idea_name"
android:scrollHorizontally="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/darkGreen"
android:textSize="27dp"
android:layout_marginTop="10dp"
android:maxLines="1"
android:textAppearance="@android:style/TextAppearance.Medium"
/>
在我设置的ViewHolder构造函数的RecyclerView中
textView.setSelected(true);
但它不起作用。有没有人有想法解决这个问题?
感谢。
答案 0 :(得分:1)
所以这就是答案:
我将TextView放在HorizontalScrollView中,并将以下代码添加到我的适配器中以供RecyclerView使用:
private void animateTextView(TextView mTextView) {
int textWidth = getTextViewWidth(mTextView);
int displayWidth = getDisplayWidth(mContext);
/* Start animation only when text is longer than dislay width. */
if(displayWidth<=textWidth) {
Animation mAnimation = new TranslateAnimation(
0, -textWidth,
0, 0);
mAnimation.setDuration(10000); // Set custom duration.
mAnimation.setStartOffset(1000); // Set custom offset.
mAnimation.setRepeatMode(Animation.RESTART); // This will animate text back ater it reaches end.
mAnimation.setRepeatCount(Animation.INFINITE); // Infinite animation.
mTextView.startAnimation(mAnimation);
}
}
private int getDisplayWidth(Context context) {
int displayWidth;
WindowManager windowManager = (WindowManager)context.getSystemService(
Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point screenSize = new Point();
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB_MR2) {
display.getSize(screenSize);
displayWidth = screenSize.x;
} else {
displayWidth = display.getWidth();
}
return displayWidth;
}
private int getTextViewWidth(TextView textView) {
textView.measure(0, 0); // Need to set measure to (0, 0).
return textView.getMeasuredWidth();
}
用以下内容开始动画:
animateTextView(txtView);
注意:不再需要自定义TextView,只需使用普通的TextView。