Last active
April 14, 2019 15:02
-
-
Save amit-bhandari/b65cbfc2c9ef92702c9d8cd24fb0bc89 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FragmentQuote extends LifecycleFragment{ | |
private QuoteViewModel quoteViewModel; //data model | |
private SwipeRefreshLayout swipeRefreshLayout; //swipe to refresh data | |
private RecyclerView recyclerView; | |
private AdapterQuotes adapterQuotes; | |
@Nullable | |
@Override | |
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { | |
View view = inflater.inflate(R.layout.fragment_quote,container,false); | |
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_quotes); | |
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_to_refresh); | |
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { | |
@Override | |
public void onRefresh() { | |
//changes will be reflected automatically, thanks to LiveData | |
quoteViewModel.refreshData(); | |
} | |
}); | |
//set up recycler view | |
adapterQuotes = new AdapterQuotes(getContext()); | |
recyclerView.setAdapter(adapterQuotes); | |
recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getContext())); | |
return view; | |
} | |
@Override | |
public void onActivityCreated(@Nullable Bundle savedInstanceState) { | |
super.onActivityCreated(savedInstanceState); | |
//create dataModel object | |
//remember, doesn’t matter how many times this method called, same object will be returned | |
quoteViewModel = ViewModelProviders.of(this).get(QuoteViewModel.class); | |
quoteViewModel.init( getArguments().getString("category"),getArguments().getInt("count")); | |
//observer data for any changes | |
//no need to unregister this receiver anywhere, lifecycle aware components, duh | |
quoteViewModel.getQuote().observe(this, new Observer<List<Quote>>() { | |
@Override | |
public void onChanged(@NonNull List<Quote> quote) { | |
if(quote.size()==0) return;; | |
adapterQuotes.insertItems(quote); | |
recyclerView.scrollToPosition(0); | |
if(swipeRefreshLayout.isRefreshing()){ | |
swipeRefreshLayout.setRefreshing(false); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment