How to use Android to realize the Lyric display effect of Music player
这篇文章主要介绍了如何使用Android实现音乐播放器歌词显示效果,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
首先实现这种效果有两种方式:
1.自定义View里重载onDraw方法,自己绘制歌词
2.用ScrollView实现
第一种方式比较精确,但要支持滑动之后跳转播放的话难度很大,所以我选择第二种,自定义ScrollView。
一.自定义LycicView extends ScrollView
里面包括一个空白布局,高度是LycicView的一半,再是一个布局存放歌词的,最后是一个空白布局高度是LycicView的一半。
这里动态的向第二个布局里面添加了显示歌词的TextView,并利用ViewTreeObserver得到每个textview的高度,方便知道每个textview歌词所要滑动到的高度。
public class LycicView extends ScrollView { LinearLayout rootView;//父布局 LinearLayout lycicList;//垂直布局 ArrayList lyricItems = new ArrayList();//每项的歌词集合 ArrayList lyricTextList = new ArrayList();//每行歌词文本集合,建议先去看看手机音乐里的歌词格式和内容 ArrayList lyricTimeList = new ArrayList();//每行歌词所对应的时间集合 ArrayList lyricItemHeights;//每行歌词TextView所要显示的高度 int height;//控件高度 int width;//控件宽度 int prevSelected = 0;//前一个选择的歌词所在的item public LycicView(Context context) { super(context); init(); } public LycicView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public LycicView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init(){ rootView = new LinearLayout(getContext()); rootView.setOrientation(LinearLayout.VERTICAL); //创建视图树,会在onLayout执行后立即得到正确的高度等参数 ViewTreeObserver vto = rootView.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { height = LycicView.this.getHeight(); width = LycicView.this.getWidth(); refreshRootView(); } }); addView(rootView);//把布局加进去 } /** * */ void refreshRootView(){ rootView.removeAllViews();//刷新,先把之前包含的所有的view清除 //创建两个空白view LinearLayout blank1 = new LinearLayout(getContext()); LinearLayout blank2 = new LinearLayout(getContext()); //高度平分 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width,height/2); rootView.addView(blank1,params); if(lycicList !=null){ rootView.addView(lycicList);//加入一个歌词显示布局 rootView.addView(blank2,params); } } /** *设置歌词, */ void refreshLyicList(){ if(lycicList == null){ lycicList = new LinearLayout(getContext()); lycicList.setOrientation(LinearLayout.VERTICAL); //刷新,重新添加 lycicList.removeAllViews(); lyricItems.clear(); lyricItemHeights = new ArrayList(); prevSelected = 0; //为每行歌词创建一个TextView for(int i = 0;i=16 lyricItemHeights.add(index,textView.getHeight());//将高度添加到对应的item位置 } }); lycicList.addView(textView); lyricItems.add(index,textView); } } } /** * 滚动到index位置 */ public void scrollToIndex(int index){ if(index < 0){ scrollTo(0,0); } //计算index对应的textview的高度 if(index < lyricTextList.size()){ int sum = 0; for(int i = 0;i