Android HorizontalScrollView

2017-09-13 10:43:20来源:网络收集作者:程序诗人人点击

分享

xml布局


Android:id="@+id/hsv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
android:id="@+id/ll_head"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >


android:id="@+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

java


//全局变量


LinearLayout llHead;
HorizontalScrollView hsv;
ViewPager viewpager;
private String[] titles;
private ArrayList textViewList;
//展示内容


ButterKnife.bind(this);
titles = new String[] { "头条", "娱乐", "科技", "信息", "八卦", "北京", "上海", "天津",
"重庆", "大大燕网" };
textViewList = new ArrayList();
for (int i = 0; i < titles.length ; i++) {
TextView textView = new TextView(ViewPagerIndacaterActivity.this);
textView.setText(titles[i]);
textView.setTextSize(20);
textView.setId(i+1000);
textView.setOnClickListener(this);
//先定义出来layoutParams,把要配的配置等封装到layoutParams,
if(i ==0){
textView.setTextColor(Color.RED);
}else {
textView.setTextColor(Color.BLACK);
}
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(20,10,20,10);
//添加view的时候,用参数;
llHead.addView(textView,layoutParams);
textViewList.add(textView);
}
MAdapter mAdapter = new MAdapter(getSupportFragmentManager());
viewpager.setAdapter(mAdapter);
//设置viewpager滑动的监听;
viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
for (int i = 0; i < textViewList.size(); i++) {
if (position == i) {
textViewList.get(i).setTextColor(Color.RED);
} else {
textViewList.get(i).setTextColor(Color.BLACK);
}
}
//让scrollView滑动
TextView textView = textViewList.get(position);
//20为margin值;
int width = textView.getWidth()+20;
hsv.scrollTo(width ,0);
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
class MAdapter extends FragmentPagerAdapter{
public MAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return IndicaterFragment.getInstance(textViewList.get(position).getText().toString());
}
@Override
public int getCount() {
return textViewList.size();
}
}
//实现onClick方法
@Override
public void onClick(View v) {
int id = v.getId();
viewpager.setCurrentItem(id-1000);
}






最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台