多重布局viewpager一个片段 [英] multiple layout viewpager with one fragment

查看:220
本文介绍了多重布局viewpager一个片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须清楚,我正在寻找一个例子或回答,我可以用在viewpager各种不同的充布局设计和数据中的所有页面是动态的,所有页面可以由用户交互。

我的用例和目前对这个问题的办法:

所以,我有8个不同类型的题型,所以我创建了布局为他们所有。此外,我在为这些布局视图中的数据必须通过Java来填充地图有获取的数据从sqlite的数据库。

但测试可能包含25个问题有不同的布局超出上述8而所有这些25题我想用一个 Viewpager 片段,将返回的基础上通过的问题类型值出我的Java图所需的布局。

我对这个apporach:

我已经创建了一个活动,虚增其与viewpager布局:

R.layout.practice_pager

< XML版本=1.0编码=UTF-8&GT?; < android.support.v4.view.ViewPager的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android         机器人:ID =@ + ID / test_container         机器人:layout_width =match_parent         机器人:layout_height =match_parent/>

*的活动编辑code *

 公共类TestActivity扩展FragmentData实现FragmentData {

            FragmentManager经理= getSupportFragmentManager();
            私人ViewPager mViewPager;
            私人MyFragmentPagerAdapter mMyFragmentPagerAdapter;
            INT PAGE_COUNT = 0;
            GrePracticeTestRecord P =新GrePracticeTestRecord();
            私人的HashMap<整数,GrePracticeResultRecord> mPracResultMap;

            公共静态INT fragmentToReturn = 0;


            @覆盖
            保护无效的onCreate(包savedInstanceState){
                super.onCreate(savedInstanceState);
                的setContentView(R.layout.practice_pager);

                mViewPager =(ViewPager)findViewById(R.id.test_container);

           //调用此函数从sqlite的数据库获取数据,并用数据填充地图
                LoadingTestView();

                PAGE_COUNT = mPracRecordMap.size();
                    initPager();
              }

        //这里我初始化寻呼机和适配器设置为它
        公共无效initPager()
    {
     p.setQUES(mPracRecordMap.get(1).getQUES());
     p.setEXPL(mPracRecordMap.get(1).getEXPL());

     fragmentToReturn =的Integer.parseInt(mPracRecordMap.get(1).getQTYPE());
     使用setData(对);

     mMyFragmentPagerAdapter =新MyFragmentPagerAdapter(getSupportFragmentManager()的flist);
     mViewPager.setAdapter(mMyFragmentPagerAdapter);

     mViewPager.setOnPageChangeListener(新OnPageChangeListener(){

        @覆盖
        公共无效onPageSelected(INT为arg0){

            mMyFragmentPagerAdapter.notifyDataSetChanged();

            p.setQUES(mPracRecordMap.get(mViewPager.getCurrentItem()+1).getQUES());
            p.setEXPL(mPracRecordMap.get(mViewPager.getCurrentItem()+1).getEXPL());

            使用setData(对);

        }

        @覆盖
        公共无效onPageScrolled(INT为arg0,浮动ARG1,ARG2 INT){
        }

        @覆盖
        公共无效onPageScrollStateChanged(INT为arg0){
        }
    });
  }

           @覆盖
        公共无效使用setData(GrePracticeTestRecord P){
            // TODO自动生成方法存根

        }

        @覆盖
        公共GrePracticeTestRecord的getData(){
            // TODO自动生成方法存根
            返回磷;
        }
    }
 

我的适配器编辑code

 公共类MyFragmentPagerAdapter扩展FragmentStatePagerAdapter {

         私人列表<片断>片段;

        公共MyFragmentPagerAdapter(FragmentManager FM,名单,其中,片断>片段){
            超(FM);
            this.fragments =片段;
        }

        / **当一个页面被请求创建*这个方法将被调用/
        @覆盖
        公共片段的getItem(INT位置){
            的System.out.println(位置值+位置);
            返回this.fragments.get(位置);
        }


        / **返回的页面数量* /
        @覆盖
        公众诠释getCount将(){
            返回this.fragments.size();
        }

        @覆盖
        公众诠释getItemPosition(Object对象){
            // TODO自动生成方法存根
            返回MyFragmentPagerAdapter.POSITION_NONE;
        }
    }
 

接口FragmentData

 公共接口FragmentData {
    公共无效使用setData(GrePracticeTestRecord P);
    公共GrePracticeTestRecord的getData();
}
 

TestFragment编辑code

公共类TestFragment扩展片段{

  AnswerEnterListener回调;
FragmentData fD的;
按钮submitAnswer;
的EditText userAnswer;

TextView的QTEXT,EXPL;

@覆盖
公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
        捆绑savedInstanceState){
          返回inflater.inflate(R.layout.qtype1,集装箱,假);
}

公共接口AnswerEnterListener
{
    公共无效onInputAnswer(字符串ANS);
}

@覆盖
公共无效onAttach(活动活动){
    super.onAttach(活动);

    尝试 {
        回调=(AnswerEnterListener)的活动;
        fD的=(FragmentData)的活动;
    }赶上(例外五){
        // TODO:处理异常
    }
}

@覆盖
公共无效onActivityCreated(包savedInstanceState){
    super.onActivityCreated(savedInstanceState);


    QTEXT =(TextView中)getActivity()findViewById(R.id.question_text)。
    EXPL =(TextView中)getActivity()findViewById(R.id.explanation_text)。


    qText.setText(Html.fromHtml(fD.getData()getQUES())。);
    expl.setText(Html.fromHtml(fD.getData()getEXPL())。);

}
 

}

类似TestFragment,我没有其他的片段了。每一个布局类型。

的问题:

  • 在第一个布局重复2次,第一次,也是我刷当年数据的位置是错误的。
  • 这是正确的做法,我已经提议由有人说,你应该使用三个片段和更新数据的左和右的片段,但是这次居然弹开了我。任何人都可以分享它,或者在博客一个很好的例子。
解决方案
  

我必须清楚,我正在寻找一个例子或回答在那里我可以   使用在viewpager各种不同的充布局设计和数据在所有   该网页将是动态的,所有页面可以通过将互动   用户。

这应该是很容易做,但你似乎已经复杂化这个有很多。你需要做的是这样的:

获得从数据库中的数据与LoadingTestView();功能。

初​​始化 ViewPager 并设置它的适配器。该适配器将根据什么标准,你必须回到正确的片段,比如在的getItem()方法。

在片段,从中应通过一些方法公开数据的活动检索数据。

我做了一个简单的例子,你可以找到<一href="https://github.com/luksprog/DroidPlayground/blob/master/src/com/luksprog/playground/fragment/TestLikeImplem.java"相对=nofollow>这里。

I must clear that I am looking for an example or answer where I can use various differnt layout designs in a viewpager and the data in all the pages would be dynamic and all pages can be interacted by the user.

My Use Case and current approach towards the problem :

So I have got 8 different types of question types and so I have created layouts for all of them. Also I the data in the views for these layouts has to be populated via java Map that has fetched data from the sqlite DB.

But a test may contain 25 questions with different layouts out of the above 8. And for all these 25 questions I want to use a Viewpager and a Fragment that will return the required layout based on the passed question type value out of my java map.

My apporach towards this :

I have created an activity and have inflated it with a viewpager layout :

R.layout.practice_pager

<?xml version="1.0" encoding="utf-8"?> <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/test_container" android:layout_width="match_parent" android:layout_height="match_parent" />

*Activity Edited code *

       public class TestActivity extends FragmentData implements FragmentData{

            FragmentManager manager=getSupportFragmentManager();
            private ViewPager mViewPager;  
            private MyFragmentPagerAdapter mMyFragmentPagerAdapter;
            int PAGE_COUNT = 0;
            GrePracticeTestRecord p=new GrePracticeTestRecord();
            private HashMap<Integer, GrePracticeResultRecord> mPracResultMap;

            public static int fragmentToReturn=0;


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

                mViewPager = (ViewPager) findViewById(R.id.test_container);  

           //This function is called to fetch the data from sqlite db and fill the map with data
                LoadingTestView();

                PAGE_COUNT=mPracRecordMap.size();
                    initPager();
              }

        //here I initialize the pager and set the adapter to it
        public void initPager()
    {
     p.setQUES(mPracRecordMap.get(1).getQUES());
     p.setEXPL(mPracRecordMap.get(1).getEXPL());    

     fragmentToReturn=Integer.parseInt(mPracRecordMap.get(1).getQTYPE());
     setData(p);

     mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),fList);  
     mViewPager.setAdapter(mMyFragmentPagerAdapter);  

     mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {

            mMyFragmentPagerAdapter.notifyDataSetChanged();

            p.setQUES(mPracRecordMap.get(mViewPager.getCurrentItem()+1).getQUES());
            p.setEXPL(mPracRecordMap.get(mViewPager.getCurrentItem()+1).getEXPL());

            setData(p);

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
  }

           @Override
        public void setData(GrePracticeTestRecord p) {
            // TODO Auto-generated method stub

        }

        @Override
        public GrePracticeTestRecord getData() {
            // TODO Auto-generated method stub
            return p;
        }
    }

My Adapter Edited code

   public class MyFragmentPagerAdapter extends FragmentStatePagerAdapter{

         private List<Fragment> fragments;

        public MyFragmentPagerAdapter(FragmentManager fm,List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        /** This method will be invoked when a page is requested to create */
        @Override
        public Fragment getItem(int position) {
            System.out.println("value of position "+position);
            return this.fragments.get(position);
        }


        /** Returns the number of pages */
        @Override
        public int getCount() {
            return this.fragments.size();
        }

        @Override
        public int getItemPosition(Object object) {
            // TODO Auto-generated method stub
            return MyFragmentPagerAdapter.POSITION_NONE;
        }
    }

Interface FragmentData

public interface FragmentData {
    public void setData(GrePracticeTestRecord p);
    public GrePracticeTestRecord getData();
}

TestFragment Edited code

public class TestFragment extends Fragment {

AnswerEnterListener callBack;
FragmentData fD;
Button submitAnswer;
EditText userAnswer;

TextView qText,expl;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
          return inflater.inflate(R.layout.qtype1, container, false);
}

public interface AnswerEnterListener
{
    public void onInputAnswer(String ans);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    try {
        callBack=(AnswerEnterListener) activity;
        fD=(FragmentData) activity;
    } catch (Exception e) {
        // TODO: handle exception
    }
}

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


    qText=(TextView) getActivity().findViewById(R.id.question_text);
    expl=(TextView)getActivity().findViewById(R.id.explanation_text);


    qText.setText(Html.fromHtml(fD.getData().getQUES()));
    expl.setText(Html.fromHtml(fD.getData().getEXPL()));

}       

}

Similar to TestFragment , I have not the other fragments too. Each for a layout type.

Issues :

  • The first layout is repeated two times at the first time , and also when I swipe back then the position of data is misplaced.
  • Is this the right approach, I have been suggested by someone that you should use three fragments and update the left and right fragments with data , but this actually bounced off me. Can anyone share a good example of it or a blog.

解决方案

I must clear that I am looking for an example or answer where I can use various differnt layout designs in a viewpager and the data in all the pages would be dynamic and all pages can be interacted by the user.

This should be quite easy to make but you seem to have complicated this a lot. You need to do something like this:

Get the data from the database with the LoadingTestView(); function.

Initialize the ViewPager and set it's adapter. The adapter will return the proper fragment instance in the getItem() method, based on whatever criteria you have.

In the fragments, retrieve the data from the activity which should expose the data through some method.

I've made a simple example that you can find here.

这篇关于多重布局viewpager一个片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆