小部件在Android 8.0中无法更新

时间:2018-06-02 06:25:21

标签: android android-viewpager widget

每次在 Android 5.0.0 6.0 7.1.1 版本中选择新标签时,我的小部件都会更新。但它没有在 Android 8.0 中更新。我正在更新setUserVisibleHint(...)方法中的小部件。现在我想我应该在ViewPager监听器中更新小部件,但我不知道哪一个。对此有何帮助?这是我的片段代码。

public class NewsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Object>, NewsAdapter.ListItemClickListener{

private Boolean isVisible;
private static final String LOG_TAG = NewsFragment.class.getName();
private static final int NEWS_LOADER_ID = 0;
private String newsUrl;

private RecyclerView mRecyclerView;
private SwipeRefreshLayout swipeRefreshLayout;

private NewsAdapter adapter;
private TextView errorTextView;

private static final String ARRAY_LIST = "list_view";
private ArrayList<News> newsArrayList;
private static final String LAYOUT_STATE = "USATodayFragment.recycler.layout";


String newsTitlesToJson;


public static NewsFragment newInstance(String newsUrl){
    Bundle bundle = new Bundle();
    bundle.putString("url", newsUrl);


    NewsFragment fragment = new NewsFragment();
    fragment.setArguments(bundle);

    return fragment;
}

private void readBundle(Bundle bundle) {
    if (bundle != null) {
        newsUrl = bundle.getString("url");
    }
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.common_fragment_layout, container, false);


    if(savedInstanceState == null) {
        newsArrayList = new ArrayList<>();


        readBundle(getArguments());


        mRecyclerView = v.findViewById(R.id.news_recycler_view);
        errorTextView = v.findViewById(R.id.errorTextView);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(getActivity()));

        adapter = new NewsAdapter(getActivity(),newsArrayList,this);
        mRecyclerView.setAdapter(adapter);

        getLoaderManager().initLoader(NEWS_LOADER_ID, null, this);

        //UpdateNewsWidgetService.startBakingService(getContext(), (ArrayList<News>) newsArrayList);

    }else{
        newsArrayList = savedInstanceState.getParcelableArrayList(ARRAY_LIST);

        readBundle(getArguments());


        errorTextView = v.findViewById(R.id.errorTextView);
        mRecyclerView = v.findViewById(R.id.news_recycler_view);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(getActivity()));
        adapter = new NewsAdapter(getActivity(),newsArrayList,this);
        mRecyclerView.setAdapter(adapter);

        //UpdateNewsWidgetService.startBakingService(getContext(), (ArrayList<News>) newsArrayList);


    }

    return v;
}

@Override
public Loader onCreateLoader(int id, Bundle args) {

    return new GenericLoader(getActivity(),newsUrl);


}


@Override
public void onLoaderReset(Loader<Object> loader) {

}

@Override
public void onLoadFinished(Loader<Object> loader, Object data) {
    int id = loader.getId();

    if(id == NEWS_LOADER_ID){
        newsArrayList = (ArrayList<News>)data;

        if(newsArrayList !=null && !newsArrayList.isEmpty()){
            adapter.clear();
            adapter.setNewsData(newsArrayList);

        }else{
            showError();
        }
    }
}

public void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putParcelableArrayList(ARRAY_LIST,newsArrayList);
    //outState.putParcelable(LAYOUT_STATE, mRecyclerView.getLayoutManager().onSaveInstanceState());
}

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

    if(savedInstanceState != null)
    {
        Parcelable savedRecyclerLayoutState = savedInstanceState.getParcelable(LAYOUT_STATE);
        mRecyclerView.getLayoutManager().onRestoreInstanceState(savedRecyclerLayoutState);

    }
}

public void showError(){
    mRecyclerView.setVisibility(View.GONE);
    errorTextView.setVisibility(View.VISIBLE);
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if(isVisibleToUser){

        newsTitlesToJson = new Gson().toJson(newsArrayList);

        if(getActivity() != null){
            /**
             * Here is store the array list into  shared preferences. The sharedpreferences
             * will be read inside the AppWidgetProvider.
             */
            PreferenceManager.getDefaultSharedPreferences(getActivity())
                    .edit().putString("news", newsTitlesToJson)
                    .commit();



            /**
             * Updating the widget.
             */
            new UpdateNewsWidgetService().startBakingService(getActivity(), newsArrayList);
        }

        Log.v(LOG_TAG, newsTitlesToJson);

    }
}

@Override
public void onListItemClick(int clickedItemIndex) {
    Intent i = new Intent(getActivity(), DetailActivity.class);
    i.putExtra("author",newsArrayList.get(clickedItemIndex).getAuthor());
    i.putExtra("image",newsArrayList.get(clickedItemIndex).getUrlToImage());
    i.putExtra("newsTitle",newsArrayList.get(clickedItemIndex).getTitle());
    i.putExtra("description",newsArrayList.get(clickedItemIndex).getDescription());
    i.putExtra("url",newsArrayList.get(clickedItemIndex).getUrl());
    i.putExtra("date",newsArrayList.get(clickedItemIndex).getPublishedDate());
    Log.v(LOG_TAG,newsArrayList.get(clickedItemIndex).getTitle());
    startActivity(i);
}



}

和我的MainActivity。

public class MainActivity extends AppCompatActivity{
FirebaseAuth mAuth;
Toolbar toolbar;
private ViewPager mViewPager;
private SectionsPageAdapter mSectionsPagerAdapter;
private TabLayout mTabLayout;

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

    mAuth = FirebaseAuth.getInstance();


    toolbar = (android.support.v7.widget.Toolbar)findViewById(R.id.main_page_toolbar);
    setSupportActionBar(toolbar);


    mViewPager = (ViewPager)findViewById(R.id.main_TabPager);
    mSectionsPagerAdapter = new SectionsPageAdapter(getSupportFragmentManager(), this);

    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setOffscreenPageLimit(1);
    mTabLayout = (TabLayout)findViewById(R.id.main_tabs);
    //mTabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FF0000"));
    //mTabLayout.setSelectedTabIndicatorHeight((int) (5 * getResources().getDisplayMetrics().density));
    mTabLayout.setTabTextColors(Color.parseColor("#460b1f"), Color.parseColor("#ffffff"));
    mTabLayout.setupWithViewPager(mViewPager);



}

@Override
protected void onStart() {
    super.onStart();

    FirebaseUser currentUser = mAuth.getCurrentUser();

    if(currentUser == null){
        sendToStart();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main_menu,menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);

    if(item.getItemId() == R.id.main_logout_btn){
        FirebaseAuth.getInstance().signOut();
        sendToStart();

    }else if(item.getItemId() == R.id.fav_news_btn){
        Intent favIntent = new Intent(MainActivity.this,FavouriteNewsActivity.class);
        startActivity(favIntent);
    }

    return true;
}
public void sendToStart(){
    Intent startIntent = new Intent(MainActivity.this,StartActivity.class);
    startActivity(startIntent);
    finish();
}

}

1 个答案:

答案 0 :(得分:0)

如果我很好看到onLoadFinish你的schangeing适配器但没有把新的适配器设置为片段,这可能是问题