horizontalScrollView添加textview,并且点击里面的任意一个textview,字体颜色发生改变,下面的viewpager也可以改变到相应的pager页,(防今日头条里面的首页样式)

首先找到horizontalScrollView的布局及里面的子布局;

HorizontalScrollView horizontalScrollView = (HorizontalScrollView) findViewById(R.id.hor);

 LinearLayout  layout = (LinearLayout) findViewById(R.id.lin);

//给layout添加子控件;

private void setTextviewData() {
// TODO Auto-generated method stub

for (int i = 0; i < data.length; i++) {
textView = new TextView(getApplicationContext());
textView.setText(data[i]);
textView.setPadding(20, 10, 20, 10);
textView.setTextSize(15.0f);
textView.setGravity(Gravity.CENTER);
hori_lin.addView(textView);
textView.setTextColor(Color.BLACK);
textView.setTag(i);
textView.setOnClickListener(this);
}

}

//textview的点击监听事件;点击哪个,viewpager显示那一页;

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int m=(Integer) textView.getTag();

if (textView.getTag()!=null) {

TextView textView=(TextView) layout.getChildAt(m);
if (textView==v) {
pager.setCurrentItem(m);

}

}




}

 

//textview点击时改变颜色;

 

//先定义一个全局变量;

int mscreenwidth ;

//首先得到整个屏幕的宽度;

//在onCreate方法里找到屏幕管理器 计算联动的距离


WindowManager wd = getWindowManager();
//计算屏幕的宽度;
mscreenwidth = wd.getDefaultDisplay().getWidth();

 

private void selectTab(int position) {
// TODO Auto-generated method stub

for (int i = 0; i < layout.getChildCount(); i++) {
TextView childAt = (TextView) layout.getChildAt(position);
// 字体的长度;
int k = childAt.getMeasuredWidth();
// 从字体到屏幕左边的距离;
int l = childAt.getLeft();

int s = l + k / 2 - mscreenwidth / 2;
horizontalScrollView.smoothScrollTo(s, 0);

TextView child = (TextView) layout.getChildAt(i);
if (position == i) {

child.setTextColor(Color.RED);

} else {
child.setTextColor(Color.BLACK);
}

}

}

//然后给viewpager设置监听,把这个放进去就行了 

pager.setOnPageChangeListener(new OnPageChangeListener() {

@Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
selectTab(arg0);
}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub

}

@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub

}
});

posted @ 2016-03-21 08:57  zyy明天你好  阅读(652)  评论(0编辑  收藏  举报