动态更新新闻应用程序的视图(viewpager)

时间:2018-05-18 00:56:14

标签: android android-viewpager fragment

我无法实现基于Viewpager的片段的数据更新。 事实上,我有一项服务可以验证和检索在线发布的最新信息更新,并提供给我的数据库。 一旦工作完成,我应该更新屏幕,但这就是我被困住的地方。 我尝试了很多技术,但在那之前我还没有收到更新屏幕。

我对这个主题感到不知所措,以至于我没有正确的话语。 谢谢你的帮助

我的主要活动

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
    private static final String TAG = "MainActivity";
    ViewPager viewPager;
    TabLayout tabLayout;
    DrawerLayout drawer;
    NavigationView navigationView;
    ActionBarDrawerToggle toggle;
    Context mContext;
    PagerAdapter vAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mContext = this;
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        reloadData();

    }

    private void setupViewPager(ViewPager viewPager) {
        vAdapter = new PagerAdapter(getSupportFragmentManager());
        vAdapter.addFragment(new StartFragment(), "START");
        vAdapter.addFragment(new MapFragment(), "MAP");
        vAdapter.addFragment(new ListArticle(), "ARTICLES");
        viewPager.setAdapter(vAdapter);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.nav_profile:
                startActivity(new Intent(mContext, ProfileActivity.class));
                break;
            case R.id.nav_map:
                startActivity(new Intent(mContext, MapActivity.class));
                break;
            case R.id.nav_history:
                startActivity(new Intent(mContext, HistoryActivity.class));
                break;
            case R.id.nav_help:
                break;

            default:
                return false;
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }



    private void scheduleJobMatchDataUpdate(){
        JobScheduler jobScheduler = (JobScheduler)getApplicationContext()
                .getSystemService(JOB_SCHEDULER_SERVICE);

        ComponentName componentName = new ComponentName(this,
                MatchUpdatedJob.class);

        JobInfo jobInfo = null;
        //if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        jobInfo = new JobInfo.Builder(1, componentName)
                .setPeriodic(60000).setRequiredNetworkType(
                        JobInfo.NETWORK_TYPE_NOT_ROAMING)
                .setPersisted(true).build();
        // }
        jobScheduler.schedule(jobInfo);
    }

    public void reloadData() {
        scheduleJobMatchDataUpdate();
        StartFragment fragment = new StartFragment();
        if (fragment.isInLayout()) {
            fragment.data();
        }
    }
}

//My PagerAdapter

public class PagerAdapter extends FragmentStatePagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public PagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

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

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position)   {
        return mFragmentTitleList.get(position);
    }

}

    public class StartFragment extends Fragment implements ArticleAdapter.ClickCB,
        BaseSliderView.OnSliderClickListener, ViewPagerEx.OnPageChangeListener{
    static final String TAG = "StartFragment";

    public StartFragment() {
        // Let empty
    }
    LinearLayoutManager mLayoutManager;
    private SwipeRefreshLayout srl;
    ArticleAdapter mAdapter;
    Context mContext;
    List<Article> mList;
    List<Article> mListSelected = new ArrayList<>();
    Call<List<Article>> call;
    ApiService service;
    RecyclerView rcv;
    Bundle bundle;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = getActivity();
        this.mList = Article.findAll(this.mContext);
        this.bundle = savedInstanceState;
        service = RetrofitBuilder.createService(ApiService.class);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_start, container, false);
        SliderLayout mSlider = (SliderLayout) view.findViewById(R.id.slider);

        String[] imgUrl = new String[3];
        imgUrl[0] = "http://...1.jpg";
        imgUrl[1] = "http://...2.jpg";
        imgUrl[2] = "http://...3.jpg";
        for (String s: imgUrl){
            MatchSliderView sliderView = new MatchSliderView(getContext());

                sliderView
                        .image(s)
                        .description("...")
                        .setScaleType(BaseSliderView.ScaleType.Fit)
                        .setOnSliderClickListener(this);
                sliderView.bundle(new Bundle());
                sliderView.getBundle()
                        .putString("extra",s);
                mSlider.addSlider(sliderView);
            }

        mSlider.setPresetTransformer(SliderLayout.Transformer.Accordion);
        // mSlider.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
        mSlider.setCustomAnimation(new DescriptionAnimation());
        mSlider.setDuration(5000);
        mSlider.addOnPageChangeListener(this);


        rcv = (RecyclerView) view.findViewById(R.id.rcv);
        mLayoutManager = new LinearLayoutManager(MainApplication.getContext());
        mLayoutManager.setOrientation(1);
        rcv.setLayoutManager(mLayoutManager);
        rcv.setHasFixedSize(true);
        //mList = Article.findAll(this.mContext);
        this.mAdapter = new ArticleAdapter(this.mContext,
                StartFragment.this, mList, mListSelected);
        rcv.setItemViewCacheSize(mList.size());
        rcv.setAdapter(this.mAdapter);
        Flubber.with()
                .animation(Flubber.AnimationPreset.FADE_IN_UP)
                .repeatCount(1)
                .duration(2000)
                .createFor(rcv)
                .start();


        srl = (SwipeRefreshLayout)view.findViewById(R.id.swipeRefreshLayout);
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                onItemsLoadComplete();
            }
        });
        return view;
    }

    void onItemsLoadComplete() {
        loadData();
        srl.setRefreshing(false);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onSliderClick(BaseSliderView slider) {
        Toast.makeText(mContext, slider.getmTitle(),
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void removeNotify(Selection selection) {
        badgeView.decrement();
    }

    public void loadData(){
        try{
            call = service.matchs();
            call.enqueue(new Callback<List<Article>>() {
                @Override
                public void onResponse(Call<List<Article>> call, Response<List<Article>> response) {
                    if(response.isSuccessful()){
                        Article.deleteAll(mContext);
                        Article.saveAll(mContext,response.body());
                    }else{
                       Toast.makeText(mContext, "Update failed!", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<List<Article>> call, Throwable t) {
                    call.isCanceled();
                    t.printStackTrace();
                }
            });
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    public void refreshData(){
        mList.clear();
        mList.addAll(Article.findAll(this.mContext));
        mAdapter.swap((ArrayList<Article>)mList);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (srl!=null) {
            srl.setRefreshing(false);
            srl.destroyDrawingCache();
            srl.clearAnimation();
        }
    }
}


public class ArticleAdapter extends RecyclerView.Adapter<ArticleAdapter.ViewHolder> implements Filterable {
    private Context mContext;
    private static final String LOG_TAG = ArticleAdapter.class.getSimpleName();
    List<Article> mListArticles = new ArrayList<>();
    private List<Article> articleList;
    private List<Article> articleListFiltered;
    private ArticlesAdapterListener listener;

    public ArticleAdapter(Context context, List<Article> mListItems){
        this.mContext = context;
        //this.mListArticles = mListItems;

        if (mListArticles != null) {
            mListArticles.clear();
            mListArticles.addAll(mListItems);
        }
        else {
            this.mListArticles = mListItems;
        }
        notifyDataSetChanged();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_article, parent, false);
        return new ViewHolder(mContext, mListArticles, view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Article item = mListArticles.get(position);
        holder.title.setText(Html.fromHtml( " " + item.getTitre()));
        //Glide.with(this).load(item.getMedia()).into((ImageView) findViewById(R.id.media));
        if(item.getMedia() != null && item.getMedia().length() >10) {
            Picasso.with(mContext).load(item.getMedia()).into(holder.img);
        }

    }


    @Override
    public int getItemCount() {
        return mListArticles.size();
    }

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {
                String charString = charSequence.toString();
                if (charString.isEmpty()) {
                    articleListFiltered = articleList;
                } else {
                    List<Article> filteredList = new ArrayList<>();
                    for (Article row : articleList) {

                        // name match condition. this might differ depending on your requirement
                        // here we are looking for name or phone number match
                        if (row.getTitre().toLowerCase().contains(charString.toLowerCase())) {
                            filteredList.add(row);
                        }
                    }

                    articleListFiltered = filteredList;
                }

                FilterResults filterResults = new FilterResults();
                filterResults.values = articleListFiltered;
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                articleListFiltered = (ArrayList<Article>) results.values;
                notifyDataSetChanged();
            }
        };
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        private Context mContext;
        private List<Article> mItems;
        public TextView title;
        public ImageView img;

        public ViewHolder(Context context, List<Article> newsList, View view){
            super(view);
            this.mContext = context;
            this.mItems = newsList;
            this.title= (TextView)view.findViewById(R.id.title);
            this.img= (ImageView) view.findViewById(R.id.media);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, ArticleDetailActivity.class);
                    intent.putExtra("id", mItems.get(getAdapterPosition()).getId());
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent);
                }
            });
        }

    }

    public interface ArticlesAdapterListener {
        void onArticleSelected(Article article);
    }

}

public class PagerAdapter extends FragmentStatePagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public PagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

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

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position)   {
        return mFragmentTitleList.get(position);
    }
}

1 个答案:

答案 0 :(得分:0)

mAdapter.swap((ArrayList<Article>)mList);
mAdapter.notifyDataSetChanged();