2

我正在使用片段和查看器。我希望每页有不同的布局和不同的功能。我怎样才能做到这一点?目前我对每个页面都有不同的布局,但我缺乏将功能放在它后面。你能帮我解决这个问题吗?

我的片段

public class MyFragment extends Fragment{

    int mCurrentPage;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /** Getting the arguments to the Bundle object */
        Bundle data = getArguments();

        /** Getting integer data of the key current_page from the bundle */
        mCurrentPage = data.getInt("current_page", 0);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = null; //= inflater.inflate(R.layout.myfragment_layout, container,false);
        //TextView tv = (TextView ) v.findViewById(R.id.tv);
        //tv.setText("You are viewing the page #" + mCurrentPage + "\n\n" + "Swipe Horizontally left / right");

        //changeing the layout per page here
        switch(mCurrentPage){

        case 1:
            v = inflater.inflate(R.layout.main_layout, container,false);
            break;

        case 2:
            v = inflater.inflate(R.layout.main_favorite, container,false);
            break;

        case 3:
            v = inflater.inflate(R.layout.main_settings, container,false);
            break;
        }    

       return v;
    }

}

MyFragmenterPagerAdapter

public class MyFragmentPagerAdapter extends FragmentPagerAdapter{

    final int PAGE_COUNT = 3;

    /** Constructor of the class */
    public MyFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    /** This method will be invoked when a page is requested to create */
    @Override
    public Fragment getItem(int arg0) {

        MyFragment myFragment = new MyFragment();

        Bundle data = new Bundle();
        data.putInt("current_page", arg0+1);
        myFragment.setArguments(data);
        return myFragment;
    }

    /** Returns the number of pages */
    @Override
    public int getCount() {
        return PAGE_COUNT;
    }
}
4

1 回答 1

4

我希望每页有不同的布局和不同的功能。我怎样才能做到这一点?

由于您希望每个页面具有不同的功能和不同的布局,因此您应该为每个页面设置不同的布局Fragment。在你的FragmentPagerAdapter

/** This method will be invoked when a page is requested to create */
@Override
public Fragment getItem(int position) {

    switch(position) {
        case 0:
            return new MyMainFragment();
        case 1:
            return new MyFavoritesFragment();
        case 2:
            return new MySettingsFragment();
        default:
            return null;
    }
}

然后在每个中Fragment,对每个单独的布局进行膨胀onCreateView。例如,MyMainFragment它看起来像:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.main_layout, container, false);

    return v;
}

这样,每个Fragment(又名页面)都将表现为自己的 UI 逻辑部分,与其他页面分开。

于 2013-03-14T22:21:26.733 回答