使用ViewPager创建自定义Android组件

时间:2015-01-22 15:15:53

标签: android android-viewpager fragmentmanager

这是我的应用程序的布局。

enter image description here

activity_main.xml中:

<RelativeLayout 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" tools:context=".MainActivity">

    <com.test.myapp.ContainerView
        android:id="@+id/view1"
        android:layout_width="match_parent"
        android:layout_height="200dp"/>

</RelativeLayout>

container_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:orientation="horizontal">

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

</LinearLayout>

ViewPagerAdapter.java:

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

    FragmentManager mFragmentManager;

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
        mFragmentManager = fm;
    }

    @Override
    public Fragment getItem(int position) {
        return new PageFragment();
    }

    @Override
    public int getCount() {
        return 5;
    }
}

MainActivity.java:     公共类MainActivity扩展ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

ContainerView.java:

public class ContainerView extends LinearLayout {

    public ContainerView(Context context, AttributeSet attrs) {
        super(context, attrs);

        // TODO: This is very ugly, how to fix this
        ActionBarActivity activity = (ActionBarActivity) context;

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View root = inflater.inflate(R.layout.container_view, this, true);

        ViewPager viewPager = (ViewPager)root.findViewById(R.id.pager);
        ViewPagerAdapter adapter = new ViewPagerAdapter(activity.getSupportFragmentManager());
        viewPager.setAdapter(adapter);
    }
}

如您所知,ViewPagerAdapter需要FragmentManager。这就是为什么我在我的ContainerView.java中有这一行,以便我可以通过activity.getSupportFragmentManager()获取FragmentManager:

ActionBarActivity activity = (ActionBarActivity) context;

这很有效,但很难看。有没有更好的方法?感谢。

0 个答案:

没有答案