我不知道您使用的是哪个 IDE,但在 Intellij 中,您必须转到“模块设置”>“库”> 单击加号 > Java > libs(文件夹)> android-support-v4.jar。在 Eclipse 中,您可能必须转到“构建路径”>“配置构建路径”>“Java 构建路径”>“添加 JAR”>“库”> android-support-v4.jar
以扩展http://thepseudocoder.wordpress.com/2011/10/05/android-page-swiping-using-viewpager/为例:
Tab1Fragment.java:
public class Tab1Fragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.live, container,false);
TextView tv = (TextView) view.findViewById(R.id.status);
tv.setText("Fragment1");
return view;
}
}
Tab2Fragment.java:
public class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.live, container,false);
TextView tv = (TextView) view.findViewById(R.id.status);
tv.setText("Fragment2");
return view;
}
}
生活.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:id="@+id/status"/>
</LinearLayout>
主要活动(ViewPagerFragmentActivity.java):
public class ViewPagerFragmentActivity extends FragmentActivity {
private PagerAdapter mPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
//initialsie the pager
this.initialisePaging();
}
private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment2.class.getName()));
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)super.findViewById(R.id.viewpager);
pager.setAdapter(this.mPagerAdapter);
}
}
main_activity.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="@+android:id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"></android.support.v4.view.ViewPager>
</LinearLayout>
PagerAdapter.java:
public class PagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
@Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
@Override
public int getCount() {
return this.fragments.size();
}
}