ViewPager+Fragment
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ViewPager+Fragment相关的知识,希望对你有一定的参考价值。
package com.imooc.tab03;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
//可以先定义n个Fragment,然后把它加入 List<Fragment> mFragments
public class MainActivity extends FragmentActivity implements OnClickListener
{
private ViewPager mViewPager;
private FragmentPagerAdapter mAdapter;
private List<Fragment> mFragments;
private ImageButton mImgWeixin;
private ImageButton mImgFrd;
private ImageButton mImgAddress;
private ImageButton mImgSettings;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initView();
initEvent();
setSelect(1);
}
private void initEvent()
{
mImgWeixin.setOnClickListener(this);
mImgAddress.setOnClickListener(this);
mImgFrd.setOnClickListener(this);
mImgSettings.setOnClickListener(this);
}
private void initView()
{
mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
mImgWeixin = (ImageButton) findViewById(R.id.id_tab_weixin_img);
mImgFrd = (ImageButton) findViewById(R.id.id_tab_frd_img);
mImgAddress = (ImageButton) findViewById(R.id.id_tab_address_img);
mImgSettings = (ImageButton) findViewById(R.id.id_tab_settings_img);
mFragments = new ArrayList<Fragment>();
Fragment mTab01 = new WeixinFragment();
Fragment mTab02 = new FrdFragment();
Fragment mTab03 = new AddressFragment();
Fragment mTab04 = new SettingFragment();
mFragments.add(mTab01);
mFragments.add(mTab02);
mFragments.add(mTab03);
mFragments.add(mTab04);
//添加Fragment的适配器
mAdapter = new FragmentPagerAdapter(getSupportFragmentManager())
{
@Override
public int getCount()
{
return mFragments.size();
}
@Override
public Fragment getItem(int arg0)
{
return mFragments.get(arg0);
}
};
mViewPager.setAdapter(mAdapter);
}
//根据点击按钮切换界面
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.id_tab_weixin_img:
setSelect(0);
break;
case R.id.id_tab_frd_img:
setSelect(1);
break;
case R.id.id_tab_address_img:
setSelect(2);
break;
case R.id.id_tab_settings_img:
setSelect(3);
break;
default:
break;
}
}
private void setSelect(int i)
{
//setTab(i);
//设置当前的ViewPager界面
mViewPager.setCurrentItem(i);
}
}
以上是关于ViewPager+Fragment的主要内容,如果未能解决你的问题,请参考以下文章
andorid自己定义ViewPager之——子ViewPager滑到边缘后直接滑动父ViewPager