在Activity中(注意添加布局,图片,选择器,布局修改theme,继承的是FragmentActivity,导入依赖工程library)
package com.example.ykdemo;
import com.viewpagerindicator.TabPageIndicator;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
/**
* Tab标题
*/
private static final String[] TITLE = new String[] { "头条", "房产", "另一面",
"女人", "财经", "数码", "情感", "科技" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ViewPager的adapter
FragmentPagerAdapter adapter = new TabPageIndicatorAdapter(
getSupportFragmentManager());
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// 实例化TabPageIndicator然后设置ViewPager与之关联
TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(pager);
// 如果我们要对ViewPager设置监听,用indicator设置就行了
indicator.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int arg0) {
Toast.makeText(getApplicationContext(), TITLE[arg0],
Toast.LENGTH_SHORT).show();
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
/**
* ViewPager适配器
*
* @author len
*
*/
class TabPageIndicatorAdapter extends FragmentPagerAdapter {
public TabPageIndicatorAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// 新建一个Fragment来展示ViewPager item的内容,并传递参数
Fragment fragment = new Fragment();
Bundle args = new Bundle();
args.putString("arg", TITLE[position]);
fragment.setArguments(args);
return fragment;
}
@Override
public CharSequence getPageTitle(int position) {
return TITLE[position % TITLE.length];
}
@Override
public int getCount() {
return TITLE.length;
}
}
}
在Fragment中
package com.example.ykdemo;
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;
public class ItemFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View contextView = inflater.inflate(R.layout.fragment_item, container,
false);
TextView mTextView = (TextView) contextView.findViewById(R.id.textview);
// 获取Activity传递过来的参数
Bundle mBundle = getArguments();
String title = mBundle.getString("arg");
mTextView.setText(title);
return contextView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}