在Viewpager

时间:2018-01-12 10:00:02

标签: java android android-fragments okhttp

我有一个BlogActivity有7个标签。我创建了一个BlogCategoryFragment,我想在用户滚动/切换标签时重复使用或回收。
例如,当用户切换到“新闻”选项卡时,BlogCategoryFragment将用于显示新闻项,当用户切换到另一个选项卡时,BlogCategoryFragment将获取不同的文章。 See the Tabs 在不同标签中提取的所有项目共享一个BlogModel模型 问题是:
1.第一个标签中的数据无法加载 2.其他选项卡可以加载数据,但单个项目会多次出现在recycleView中。 3.滚动一次会停止应用程序。

这是我的代码:
BlogActivity

public class BlogActivity extends AppCompatActivity {
    ViewPager mViewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blog);
        //viewpager initialization
        BlogCategoryStatePagerAdapter blogCategoryStatePagerAdapter;
        blogCategoryStatePagerAdapter = new BlogCategoryStatePagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.blog_container);
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setAdapter(blogCategoryStatePagerAdapter);


        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mViewPager.getAdapter().notifyDataSetChanged();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        TabLayout tabLayout = (TabLayout) findViewById(R.id.blog_tabs);
        tabLayout.setupWithViewPager(mViewPager);
        //end viewpager
    }


    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
   public class BlogCategoryStatePagerAdapter extends FragmentPagerAdapter {
        private  int NUM_ITEMS = 7;

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

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return BlogCategoryFragment.addBlogCategory("1","yy");
                    //break;
                case 1:
                    return BlogCategoryFragment.addBlogCategory("2","tt");
                    //break;
                .........
                case 6:
                    return BlogCategoryFragment.addBlogCategory("7","gg");
                    //break;

                default:
                    return null;
            }
            //return  fragment;

        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }


        @Override
        public int getCount() {
            // Show 7 total pages.
            return NUM_ITEMS;
        }


        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return getString(R.string.title_general_category);
                case 1:
                    return getString(R.string.title_county_category);
                 ......
                case 6:
                    return getString(R.string.title_lifestyle_category);
            }
            return null;
        }


    }

}

BlogCategoryFragment

public class BlogCategoryFragment extends Fragment {
    boolean dataLoaded = false;
    public static RecyclerView blogRecycleView;
    public static BlogArticleAdapter blogArticleAdapter;
    public static List<BlogModel> blogModelList = new ArrayList<>();
    private SwipeRefreshLayout swipeRefreshLayout;
    private BlogModel blogModel;
    private Handler mHandler;
    public BlogCategoryFragment() {
        // Required empty public constructor
    }

    public static BlogCategoryFragment addBlogCategory(String categoryId, String categoryName) {
        BlogCategoryFragment fragment = new BlogCategoryFragment();
        CATEGORY_ID   = categoryId;
        CATEGORY_NAME = categoryName;
        return fragment;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && !dataLoaded){
            //loadBlogPosts;
            loadDataDirect();
            dataLoaded = true;
        }
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View listView = inflater.inflate(R.layout.fragment_blog_category,container,false);
        blogRecycleView = (RecyclerView) listView.findViewById(R.id.blogRecyclerView);
        blogArticleAdapter = new BlogArticleAdapter(blogModelList, getActivity());
        mHandler = new Handler(Looper.getMainLooper());
        //set the layout manager
        blogRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));

        blogRecycleView.setAdapter(blogArticleAdapter);
        //blogRecycleView.stopScroll();
        //setup swipe to refresh
        swipeRefreshLayout = (SwipeRefreshLayout)listView.findViewById(R.id.refreshBlogLayout);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
                android.R.color.holo_green_dark
                ,android.R.color.holo_orange_dark ,android.R.color.holo_blue_dark);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //clear list
                blogModelList.clear();
                loadDataDirect();
                //new LoadBlogPost(BlogCategoryFragment.this).execute(AppConstants.API_BLOG_URL);
                //reload from the internet
            }
        });
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                if (new AppHelper(getActivity()).isNetworkAvailable()) {
                    //loadBlogPosts();
                    loadDataDirect();
                    blogModelList.clear();
                    //new LoadBlogPost(BlogCategoryFragment.this).execute(AppConstants.API_BLOG_URL);
                }  else {
                    Toast.makeText(getContext(), "Error internet connection", Toast.LENGTH_SHORT).show();
                }

            }
        });
        //end setup swipe to refresh
        //loadBlogPosts();
        loadDataDirect();
       //new LoadBlogPost(BlogCategoryFragment.this).execute(AppConstants.API_BLOG_URL);

        return listView;
    }
    private void loadDataDirect(){
        // should be a singleton
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(AppConstants.API_BLOG_URL)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String responseData = response.body().string();
                    JSONObject jObject = new JSONObject(responseData);
                    JSONArray blogArticlesArray = jObject.getJSONArray("blog_article");
                    blogModelList.clear();
                    Log.d("BLOG", blogArticlesArray.toString());
                    //create an empty Blogmodel object


                    //loop though the data
                    for (int i = 0; i < blogArticlesArray.length(); i++) {
                        JSONObject blogItem = blogArticlesArray.getJSONObject(i);
                        blogModel = new BlogModel(
                                blogItem.getInt("id"),
                                blogItem.getString("article_title"),
                                blogItem.getString("images_url"),
                                blogItem.getString("created_at")
                        );
                        blogModelList.add(blogModel);
                        //update the BlogModel List
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                blogArticleAdapter.notifyDataSetChanged();
                            }
                        });



                    }
                    //end loop
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

哪里可能是问题?

0 个答案:

没有答案