首页 > 代码库 > 【Android实战】ScrollView+GridView+ViewPager实现导航页

【Android实战】ScrollView+GridView+ViewPager实现导航页

        按照常规思路,实现导航页有专门的TabHost或ViewPager,但自定义空间不大,再者,自己想熟悉一下多重布局和动画效果的使用,因此采用这种ScrollView+GridView+ViewPager的效果。

        其中比较麻烦的是GridView实现横向的加载,并且下面的滚动条随着滑动也得滚动和动态发生位置变化。

public class MainAct extends FragmentActivity {
	ViewPager viewPager;
	HorizontalScrollView scrollView;
	String[] titles = { "首页", "新闻", "交友", "购物", "娱乐", "视频", "阅读", "运动", "医疗",
			"食品" };
	LayoutParams textLayoutParams;
	private MyGridView gridView;
	int[] tabmoving = new int[2];
	View downView;
	long dutime = 500;
	boolean right = true;
	int old = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.scrollpager);
		textLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		textLayoutParams.setMargins(10, 10, 10, 10);
		viewPager = (ViewPager) findViewById(R.id.pager);
		scrollView = (HorizontalScrollView) findViewById(R.id.myscroll);
		gridView = (MyGridView) findViewById(R.id.gridview);
		downView = (View) findViewById(R.id.down);
		final MyAdapter adapter = new MyAdapter();

		PagerAdapter myAdapter = new PagerAdapter(getSupportFragmentManager());
		viewPager.setAdapter(myAdapter);

		int size = titles.length;
		final DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		float density = dm.density;
		int allWidth = (int) (110 * (size) * density) - (titles.length) * 10;
		final int itemWidth = (int) (100 * density);

		downView.setLayoutParams(new LayoutParams(itemWidth, 8));

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				allWidth, LinearLayout.LayoutParams.FILL_PARENT);
		gridView.setLayoutParams(params);
		gridView.setColumnWidth(itemWidth);
		gridView.setHorizontalSpacing(10);
		gridView.setStretchMode(GridView.NO_STRETCH);
		gridView.setNumColumns(size);
		gridView.setAdapter(adapter);
		viewPager.setCurrentItem(0);
		gridView.getParent().requestDisallowInterceptTouchEvent(true);
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

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

				View view = gridView.getChildAt(arg0);
				if (view == null)
					return;
				view.getLocationOnScreen(tabmoving);
				if (old <= tabmoving[0]) {
					right = true;
				} else {
					right = false;
				}
				old = tabmoving[0];

				int difvalue = http://www.mamicode.com/dm.widthPixels - tabmoving[0] - itemWidth;>

【Android实战】ScrollView+GridView+ViewPager实现导航页