ViewPager,FragmentStatePagerAdapter,ListFragment为每个片段分隔列表数据

时间:2012-03-26 21:53:13

标签: java android android-fragments fragment android-viewpager

我有一个ViewPager,其中包含动态页数。每个页面都需要从数据库中读取并显示该页面的数据集。

我将当前所选页面标题与db“username”中的第一个值进行比较,以检查数据是否与该页面相关。

我的片段虽然没有正确显示数据。我试图在onCreateView中设置一个arrayAdapter,但是没有调用每个片段的创建。在我的测试用例中,我有三个片段,user1,user2,user3。 onCreateView最初是在user1上调用的,然后只在我向后滑动到user2时再次调用,而对于user1或user3再也不会调用。

我需要能够专门为每个片段设置arrayAdapter,因为每个片段都有一个不同的值数组可供显示。

PagerAdapter

   public class ExamplePagerAdapter extends FragmentStatePagerAdapter implements TitleProvider{

        private Map<Integer, UserFragment> mPageReferenceMap = new HashMap<Integer, UserFragment>();

        public ExamplePagerAdapter(FragmentManager fm) {
            super(fm);
        }

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

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = new UserFragment();

            Bundle args = new Bundle();
            fragment.setArguments(args);        
            return fragment;
        }

        @Override
        public String getTitle(int pos) {
            return "@"+users[pos].getName();
        }

        @Override
        public void destroyItem(View container, int position, Object object) {              
            mPageReferenceMap.remove(Integer.valueOf(position));
        }
    }

UserFragment

public class UserFragment extends ListFragment {
      Context ctx;
      View v;
      Button mAddEntry;
      static int p; 
      static ArrayList<String> entryArray;

       @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            ctx = container.getContext();
            if (v != null) 
                return v;

            v = inflater.inflate(R.layout.user_fragment, container, false);
            mAddEntry = (Button) v.findViewById(R.id.entry_b);
            mAddEntry.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle b = new Bundle();
                    b.putInt("pos", p);
                    Intent mi = new Intent(v.getContext(), EntryAdd.class);
                    mi.putExtras(b);
                    startActivity(mi);
                }
            });             
            updateUserFrag();
            return v;      
       }     

       public void updateUserFrag () {         
             entryArray = new ArrayList<String>();
             StringBuilder sb = new StringBuilder();
             final DBAdapter db = new DBAdapter(ctx);
             db.open();
             Cursor c = db.getAllEntries();
             try {
                while (c.moveToNext()) {
                    if (c.getString(0).equals(MainActivity.users[p].getName())) {
                        sb.append(c.getString(1));
                        entryArray.add(sb.toString());
                    }
                }
             } catch (Exception e) {}
             c.close();
             db.close();

             ArrayAdapter<String> a = new ArrayAdapter<String>(ctx, android.R.layout.simple_list_item_1, entryArray);
             setListAdapter(a);
       }

}

基本上,我只需要一个方法,我可以用它来创建每个片段的数据。 onCreateView()并没有为每个片段调用,所以对我没用。

更新 我想我差不多了,但我无法弄清楚这最后一部分。我使用TitlePageIndicators onPageSelected方法将数据发送到我的片段处理程序。

   TitlePageIndicator indicator = (TitlePageIndicator)findViewById(R.id.indicator);
    indicator.setViewPager(pager, 0);
    indicator.setOnPageChangeListener(new OnPageChangeListener() {
         @Override
         public void onPageSelected(int position) {
              Message msg = UserFragment.handy.obtainMessage(); 
              Bundle b = new Bundle(); 
              b.putInt("m", 0); 
              b.putInt("p", position); 
              b.putStringArrayList("e", updateUserFrag(position));
              msg.setData(b); 
              UserFragment.handy.handleMessage(msg);                 
         }

处理程序

   static Handler handy = new Handler() { 
        public void handleMessage(Message msg) { 
            int p = msg.getData().getInt("p"); 
            int m = msg.getData().getInt("m"); 
            ArrayList<String> e = msg.getData().getStringArrayList("e");

            switch (m) { 
                case 0: 
                    Log.d("HANDLER", Integer.toString(p));
                    for (int i=0;i<e.size();i++) {
                        //Log.d("ENTRY", e.get(i));
                    }
                break; 
             } 
        } 
   }; 

问题在于,在调用处理程序时,已经设置了Arrayadapter,我可以找到触发刷新该数据的方法。

1 个答案:

答案 0 :(得分:1)

 @Override
     public void onPageSelected(int position) {
          Message msg = UserFragment.handy.obtainMessage(); 
          Bundle b = new Bundle(); 
          b.putInt("m", 0); 
          b.putInt("p", position); 
          b.putStringArrayList("e", updateUserFrag(position));
          msg.setData(b); 
          UserFragment.handy.handleMessage(msg);                 
     }

   public ArrayList<String> updateUserFrag (int p) {           
         entryArray = new ArrayList<String>();
         StringBuilder sb = new StringBuilder();
         DBAdapter db = new DBAdapter(this);
         db.open();
         Cursor c = db.getAllEntries();
         try {
            while (c.moveToNext()) {
                if (c.getString(0).equals(users[p].getName())) {
                    sb.append(c.getString(1));
                    entryArray.add(sb.toString());
                }
            }
         } catch (Exception e) {}
         c.close();
         db.close();
        return entryArray;           
   }

UserFragment

public class UserFragment extends ListFragment {
      Context ctx;
      View v;
      Button mAddEntry;
      static int p; 
      static ArrayList<String> entryArray;
      static ArrayAdapter<String> a;

       @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            ctx = container.getContext();
            if (v != null) 
                return v;

            v = inflater.inflate(R.layout.user_fragment, container, false);
            mAddEntry = (Button) v.findViewById(R.id.entry_b);
            mAddEntry.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle b = new Bundle();
                    b.putInt("pos", p);
                    Intent mi = new Intent(v.getContext(), EntryAdd.class);
                    mi.putExtras(b);
                    startActivity(mi);
                }
            });    
            updateUserFrag(p);
            return v;      
       }     

       public void updateUserFrag (int p) {        
             entryArray = new ArrayList<String>();
             a = new ArrayAdapter<String>(ctx, android.R.layout.simple_list_item_1, entryArray);
             setListAdapter(a);
       }

       static Handler handy = new Handler() { 
            public void handleMessage(Message msg) { 
                int p = msg.getData().getInt("p"); 
                int m = msg.getData().getInt("m"); 
                ArrayList<String> e = msg.getData().getStringArrayList("e");

                switch (m) { 
                    case 0: 
                        Log.d("HANDLER", Integer.toString(p));
                        entryArray.clear();
                        for (int i=0;i<e.size();i++) {
                            entryArray.add(e.get(i));
                        }
                        a.notifyDataSetChanged();
                    break; 
                 } 
            } 
       };      
}