Android中ViewPager和Fragment实现内容和导航栏的绑定

页面效果


逻辑代码--MainActivity

package com.example.week4_day4_viewpagerandfragment;

import java.util.ArrayList;
import java.util.List;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

	private ViewPager viewPager;//声明ViewPager
	private List<Fragment> list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);//加载布局
		viewPager = (ViewPager) findViewById(R.id.viewpager);//得到ViewPager对象
		initFragment();//调用Fragment
		tab();//导航栏
		//绑定适配器
		viewPager
				.setAdapter(new MyFragmentAdapter(getSupportFragmentManager(),list) );
		//导航栏绑定数据源
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				for (int i = 0; i < list.size(); i++) {
					tvs[i].setBackgroundColor(Color.BLUE);
				}
				tvs[arg0].setBackgroundColor(Color.YELLOW);
			}
			
			@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
				
			}
		});
	}

	public void initFragment() {
		list = new ArrayList<Fragment>();

		MyFragment fragment1 = new MyFragment();
		Bundle bundle = new Bundle();
		bundle.putInt("index", 1);
		fragment1.setArguments(bundle);

		MyFragment fragment2 = new MyFragment();
		bundle = new Bundle();
		bundle.putInt("index",2);
		fragment2.setArguments(bundle);

		MyFragment fragment3 = new MyFragment();
		bundle = new Bundle();
		bundle.putInt("index", 3);
		fragment3.setArguments(bundle);
		list.add(fragment1);
		list.add(fragment2);
		list.add(fragment3);
	}

	private TextView[] tvs;
	//导航栏
	public void tab(){
		LinearLayout layout=(LinearLayout) findViewById(R.id.linear1);
		tvs=new TextView[3];
		for (int i = 0; i < tvs.length; i++) {
			tvs[i]=(TextView) layout.getChildAt(i);
			tvs[i].setTag(i);
			tvs[i].setBackgroundColor(Color.BLUE);
			tvs[i].setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					viewPager.setCurrentItem((Integer) v.getTag());
					
				}
			});
			tvs[0].setBackgroundColor(Color.YELLOW);
		}
	}

}
自定义适配器

package com.example.week4_day4_viewpagerandfragment;

import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

/**
 * 自定义FragmentPagerAdapter的适配器
 * 专门存放Fragment数据
 * 
 */
public class MyFragmentAdapter extends FragmentPagerAdapter {

	private List<Fragment> list;
	public MyFragmentAdapter(FragmentManager fm,List<Fragment> list) {
		super(fm);
		this.list=list;
	
	}
	/**
	 * 根据指定下标返回对应的Fragment对象
	 */
	@Override
	public Fragment getItem(int arg0) {
	
		return list.get(arg0);
	}
	/**
	 * 适配器中Fragment的数量
	 */
	@Override
	public int getCount() {
		
		return list.size();
	}
	

}
Fragment

package com.example.week4_day4_viewpagerandfragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@SuppressLint("NewApi")
public class MyFragment extends Fragment {

	private TextView tv;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Bundle bundle = getArguments();
		View view = inflater.inflate(R.layout.item, null);
		tv = (TextView) view.findViewById(R.id.tv);
		if (bundle != null) {
			int tab = bundle.getInt("index");
			switch (tab) {
			case 1:
				tv.setText("新闻");
				break;
			case 2:
				tv.setText("娱乐");
				break;
			case 3:
				tv.setText("体育");
				break;

			default:
				break;
			}
		}
		return view;
	}
}
界面布局--main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linear1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="新闻" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="娱乐" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="体育" />
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
界面布局--item

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView 
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textColor="#ff0000"
        android:textSize="20sp"/>

</RelativeLayout>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我会为您讲解关于AndroidViewPager和Fragment的使用。 ViewPager和FragmentAndroid非常常用的组件,他们可以一起使用来实现滑动页面效果。ViewPager是一个可以左右滑动切换页面的布局容器,而Fragment作为ViewPager的子页面,可以在ViewPager进行动态添加和移除。 下面我们将分别介绍ViewPager和Fragment的使用。 ## ViewPager的使用 ### 1.布局文件 在布局文件,我们需要使用ViewPager作为容器,将需要滑动切换的页面放入其。如下所示: ``` <androidx.viewpager.widget.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent"/> ``` ### 2.创建Adapter 我们需要创建一个Adapter继承自PagerAdapter,并重写以下方法: ``` public class MyPagerAdapter extends PagerAdapter { private List<Fragment> mFragments; public MyPagerAdapter(List<Fragment> fragments) { mFragments = fragments; } @Override public int getCount() { return mFragments.size(); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == object; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { Fragment fragment = mFragments.get(position); container.addView(fragment.getView()); return fragment.getView(); } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView((View) object); } } ``` ### 3.设置Adapter 在Activity或Fragment,我们需要创建ViewPager的实例,并设置Adapter。如下所示: ``` ViewPager viewPager = findViewById(R.id.viewPager); List<Fragment> fragments = new ArrayList<>(); fragments.add(new Fragment1()); fragments.add(new Fragment2()); fragments.add(new Fragment3()); MyPagerAdapter adapter = new MyPagerAdapter(fragments); viewPager.setAdapter(adapter); ``` 这样,我们就完成了ViewPager的使用。 ## Fragment的使用 ### 1.创建Fragment 我们需要创建一个继承自Fragment的类,并重写以下方法: ``` public class Fragment1 extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment1, container, false); return view; } } ``` ### 2.布局文件 我们需要在Fragment添加布局文件,如下所示: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:text="Fragment1" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> ``` 这样,我们就完成了Fragment的使用。 ## ViewPager和Fragment的结合使用 通过以上介绍,我们已经知道了如何使用ViewPager和Fragment了。现在我们需要将它们结合起来使用。 ### 1.创建Fragment 我们需要创建多个Fragment作为ViewPager的子页面。 ### 2.创建Adapter 我们需要创建一个PagerAdapter,将Fragment添加到ViewPager。如上所示,我们已经创建了一个MyPagerAdapter。 ### 3.设置Adapter 在Activity或Fragment,我们需要创建ViewPager的实例,并设置Adapter。如上所示,我们已经使用ViewPager的setAdapter方法设置了MyPagerAdapter。 这样,我们就完成了ViewPager和Fragment的结合使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值