HorizontalScrollView是一个滚动视图,可以帮助我们实现菜单栏之类的方法,实现左滑动右滑动.
常用于做一些APP的导航条,那么我们如何进行实现呢?
首先肯定是声明布局,做一个示范:
(这是在一个相对布局中做的 上面是我们的HorizontalScrollView,下面是一个可以滑动的ViewPager)
实现了布局,接下来就该声明控件的ID以及一些数据的声明,(我的数据是自定义的)
private HorizontalScrollView hs;
private LinearLayout linearLayout;
private ViewPager viewPager;
private String[] titles = {"头条", "娱乐", "科技", "信息", "八卦", "北京", "上海", "天津","重庆", "大大燕网" };
List list;
接着是找到资源ID (我自动省略了)
接下来就是往list中添加TextView
list = new ArrayList<>();
for (int i = 0; i < titles.length; i++){
TextView textView = new TextView(this);
textView.setText(titles[i]);
textView.setTextSize(20);
textView.setId(i+1000);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int id = view.getId();
viewPager.setCurrentItem(id-1000);
}
});
//刚进程序第一个默认红色,其他为黑色
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(50,10,50,10);接下来就是做一个Fragment类 定义视图(话不多说,直接上代码)
public class Fragment1 extends Fragment {
public static Fragment getinstance(String title){
//创建Fragment1
Fragment1 fragment1 = new Fragment1();
//创建bundle
Bundle bundle = new Bundle();
//添加值
bundle.putString("title",title);
//把值添加到Arguments中
fragment1.setArguments(bundle);
return fragment1;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//获取Arguments
Bundle arguments = getArguments();
//获取值
String title = arguments.getString("title");
//创建textview
TextView textView = new TextView(getActivity());
//设置值
textView.setText(title);
return textView;
}
再回到Activity中定义咱们的类
最后设置适配器
//为viewpager设置适配器
viewPager.setAdapter(new Myadapter(getSupportFragmentManager()));
//viewpager的监听
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//滑动改变颜色
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//list中存的是 textview
for (int i = 0; i < list.size(); i++) {
if(position==i){
list.get(i).setTextColor(Color.RED);
}else{
list.get(i).setTextColor(Color.BLACK);
}
}
//获取当前的textview
TextView textView = list.get(position);
//width是每次滑动的距离
int width = textView.getWidth()+10;
//让scrollView滑动 滑动距离是textview之间的间距
hs.scrollTo(width*position,0);
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
希望这篇文章对一些人有帮助~