Android实现TextView字体过长时滚动(跑马灯)显示

今天帮同事写一个小的对话框,TextView文字较短时有多长显示多长,在文字较长时左右滚动显示文字,实现效果如下


实现代码为

class MainActivity extends Activity {

    TextView marqueeTextViewShort, marqueeTextViewLong;

    FrameLayout mainLayout;
    LinearLayout layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainLayout = new FrameLayout(this);
        mainLayout.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        setContentView(mainLayout);

        layout = new LinearLayout(this);
        layout.setLayoutParams(new LinearLayout.LayoutParams(500, 500));
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setGravity(Gravity.CENTER);
        mainLayout.addView(layout);

        marqueeTextViewShort = new TextView(this);
        marqueeTextViewShort.setMaxWidth(400);
        marqueeTextViewShort.setText("这是一个短测试");
        marqueeTextViewShort.setTextSize(20);
        marqueeTextViewShort.setTextColor(Color.BLACK);
        marqueeTextViewShort.getPaint().setFakeBoldText(true);
        marqueeTextViewShort.setSelected(true);
        marqueeTextViewShort.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        marqueeTextViewShort.setMarqueeRepeatLimit(-1);//-1代表一直重复
        marqueeTextViewShort.setSingleLine(true);
        layout.addView(marqueeTextViewShort);

        marqueeTextViewLong = new TextView(this);
        marqueeTextViewLong.setMaxWidth(400);
        marqueeTextViewLong.setText("这是一个长测试,这是一个长测试,这是一个长测试,这是一个长测试");
        marqueeTextViewLong.setTextSize(20);
        marqueeTextViewLong.setTextColor(Color.RED);
        marqueeTextViewLong.getPaint().setFakeBoldText(true);
        marqueeTextViewLong.setSelected(true);
        marqueeTextViewLong.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        marqueeTextViewLong.setMarqueeRepeatLimit(-1);//-1代表一直重复
        marqueeTextViewLong.setSingleLine(true);
        layout.addView(marqueeTextViewLong);
    }
}

你可能感兴趣的:(Android)