转载请注明出处 http://blog.csdn.net/qq_31715429/article/details/52786614
本文出自:猴菇先生的博客
需求是 一个集合中,每个对象的文字后面坠一个图片,然后整体滚动,效果如下
demo代码如下
1.activity_main.xml:
<HorizontalScrollView
android:id="@+id/sv"
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="#E1F4FF"
android:scrollbars="none">
<LinearLayout
android:id="@+id/ll"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal" />
</HorizontalScrollView>
2.MainActivity.java:
public class MainActivity extends AppCompatActivity {
private List<DataBean> mList;
private HorizontalScrollView mSv;
private LinearLayout mLl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
initView();
}
/**
* 初始化数据
*/
private void initData() {
mList = new ArrayList<>();
for (int i = 0; i < 6; i++) {
DataBean bean = new DataBean();
bean.setName("WTI");
bean.setPrice("1000.0");
bean.setTrend("up");
mList.add(bean);
}
}
/**
* 初始化布局
*/
private void initView() {
mSv = (HorizontalScrollView) findViewById(R.id.sv);
mLl = (LinearLayout) findViewById(R.id.ll);
mSv.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
//设置ScrollView取消手动滑动
return true;
}
});
//动态添加TextView
float scrollWidth = 0f;//滚动的总宽度
for (int i = 0; i < mList.size(); i++) {
DataBean bean = mList.get(i);
TextView tv = new TextView(this);
tv.setText(" " + bean.getName() + " " + bean.getPrice() + " ");
//给TextView右边坠一个图片,四个参数分别代表在left、top、right、bottom添加图片,并使用原始大小
tv.setCompoundDrawablesWithIntrinsicBounds(null, null,
getResources().getDrawable(R.mipmap.ic_launcher), null);
//测量每个TextView的宽度
int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
tv.measure(spec, spec);
//每个TextView的宽度相加得到总宽度
scrollWidth += tv.getMeasuredWidth();
Log.e("--> ", String.valueOf(scrollWidth));
mLl.addView(tv);
}
startScroll(scrollWidth);
}
/**
* 开始滚动
*/
private void startScroll(float scrollWidth) {
if (scrollWidth != 0) {
final long duration = (long) (scrollWidth* 5);//动画时长
//属性动画位移,从屏幕右边向左移动到屏幕外scrollWidth长度的距离
ObjectAnimator anim = ObjectAnimator.ofFloat(mLl, "translationX", getScreenWidth(), -scrollWidth);
anim.setDuration(duration);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatMode(ValueAnimator.RESTART);//无限重复
anim.setRepeatCount(ValueAnimator.INFINITE);
anim.start();
}
}
/**
* 获得屏幕宽度
*/
private int getScreenWidth() {
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}
}
需要注意的是,如果下拉刷新数据,需要在动态添加TextView之前添加
mLl.removeAllViews();
mLl.clearAnimation();
否则会造成动画混乱、mLl重复添加多个TextView的问题