Android下 一个自定义VIEW实现简单的弹幕效果

来源:互联网 发布:淘宝已售 是月销量吗 编辑:程序博客网 时间:2024/05/21 16:48

Android下 一个自定义VIEW实现简单的弹幕效果


先上图:



xml布局:

 <com.co.barrage.BarrageView        android:id="@+id/barrage_view"        android:layout_width="match_parent"        android:layout_height="match_parent"        />

自定义view:

public class BarrageView  extends RelativeLayout {    private Context mContext;    private BarrageHandler mHandler = new BarrageHandler();    private Random random = new Random(System.currentTimeMillis());    private static final long BARRAGE_GAP_MIN_DURATION = 1000;//两个弹幕的最小间隔时间    private static final long BARRAGE_GAP_MAX_DURATION = 2000;//两个弹幕的最大间隔时间    private int maxSpeed = 10000;//速度,ms    private int minSpeed = 5000;//速度,ms    private int maxSize = 30;//文字大小,dp    private int minSize = 15;//文字大小,dp    private int totalHeight = 0;    private int lineHeight = 0;//每一行弹幕的高度    private int totalLine = 0;//弹幕的行数    private List<String> messageList = new ArrayList<>();    public BarrageView(Context context) {        this(context, null);    }    public BarrageView(Context context, AttributeSet attrs) {        this(context, attrs, 0);    }    public BarrageView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        mContext = context;        init();    }    private void init() {        int duration = (int) ((BARRAGE_GAP_MAX_DURATION - BARRAGE_GAP_MIN_DURATION) * Math.random());        mHandler.sendEmptyMessageDelayed(0, duration);    }    public void addMessage(String message) {        messageList.add(message);    }    @Override    public void onWindowFocusChanged(boolean hasWindowFocus) {        super.onWindowFocusChanged(hasWindowFocus);        totalHeight = getMeasuredHeight();        lineHeight = getLineHeight();        totalLine = totalHeight / lineHeight;    }    private void generateItem() {        if (messageList.size() > 0) {            BarrageItem item = new BarrageItem();            String tx = messageList.remove(0);            int sz = (int) (minSize + (maxSize - minSize) * Math.random());            item.textView = new TextView(mContext);            item.textView.setText(tx);            item.textView.setTextSize(sz);            item.textView.setTextColor(Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256)));            item.textMeasuredWidth = (int) getTextWidth(item, tx, sz);            item.moveSpeed = (int) (minSpeed + (maxSpeed - minSpeed) * Math.random());            if (totalLine == 0) {                totalHeight = getMeasuredHeight();                lineHeight = getLineHeight();                totalLine = totalHeight / lineHeight;            }            item.verticalPos = random.nextInt(totalLine) * lineHeight;            showBarrageItem(item);        }    }    private void showBarrageItem(final BarrageItem item) {        int leftMargin = this.getRight() - this.getLeft() - this.getPaddingLeft();        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);        params.addRule(RelativeLayout.ALIGN_PARENT_TOP);        params.topMargin = item.verticalPos;        this.addView(item.textView, params);        Animation anim = generateTranslateAnim(item, leftMargin);        anim.setAnimationListener(new Animation.AnimationListener() {            @Override            public void onAnimationStart(Animation animation) {            }            @Override            public void onAnimationEnd(Animation animation) {                item.textView.clearAnimation();                BarrageView.this.removeView(item.textView);            }            @Override            public void onAnimationRepeat(Animation animation) {            }        });        item.textView.startAnimation(anim);    }    private TranslateAnimation generateTranslateAnim(BarrageItem item, int leftMargin) {        TranslateAnimation anim = new TranslateAnimation(leftMargin, -item.textMeasuredWidth, 0, 0);        anim.setDuration(item.moveSpeed);        anim.setInterpolator(new AccelerateDecelerateInterpolator());        anim.setFillAfter(true);        return anim;    }    /**     * 计算TextView中字符串的长度     *     * @param text 要计算的字符串     * @param Size 字体大小     * @return TextView中字符串的长度     */    public float getTextWidth(BarrageItem item, String text, float Size) {        Rect bounds = new Rect();        TextPaint paint;        paint = item.textView.getPaint();        paint.getTextBounds(text, 0, text.length(), bounds);        return bounds.width();    }    /**     * 获得每一行弹幕的最大高度     *     * @return     */    private int getLineHeight() {      /*  BarrageItem item = new BarrageItem();        String tx = itemText[0];        item.textView = new TextView(mContext);        item.textView.setText(tx);        item.textView.setTextSize(maxSize);        Rect bounds = new Rect();        TextPaint paint;        paint = item.textView.getPaint();        paint.getTextBounds(tx, 0, tx.length(), bounds);        return bounds.height();*/        return 50;    }    class BarrageHandler extends Handler {        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            generateItem();            //每个弹幕产生的间隔时间随机            int duration = (int) ((BARRAGE_GAP_MAX_DURATION - BARRAGE_GAP_MIN_DURATION) * Math.random());            this.sendEmptyMessageDelayed(0, duration);        }    }}

使用:、简单的弄了一个EditText和按钮,点击按钮让编辑框里的内容发到弹幕上

public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private BarrageView mBarrageView;    private EditText mEditText;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        findViewById(R.id.send).setOnClickListener(this);        mBarrageView= (BarrageView) findViewById(R.id.barrage_view);        mEditText= (EditText) findViewById(R.id.et);    }    @Override    public void onClick(View view) {        mBarrageView.addMessage(mEditText.getText().toString());    }}


第一次发,可能写的比价草率,大家凑合看哈~

原创粉丝点击