Article Fragment
Learn how to implement a WebView in the Android application.
We'll cover the following...
WebView
implementation
In the previous lesson, we introduced ourselves to WebView
. Now, we’ll implement WebView
to enable reading articles within our application for a more interactive user experience.
Let’s look at the code.
Press + to interact
class ArticleFragment : Fragment(R.layout.fragment_article) {lateinit var viewModel: NewsViewModelval args: ArticleFragmentArgs by navArgs()private var fragmentArticleBinding: FragmentArticleBinding? = nulloverride fun onViewCreated(view: View, savedInstanceState: Bundle?) {super.onViewCreated(view, savedInstanceState)val binding = FragmentArticleBinding.bind(view)fragmentArticleBinding = bindingval newsRepository = NewsRepository(ArticleDatabase(requireContext() as NewsActivity))val viewModelProviderFactory =NewsViewModelProvider(activity?.application!!, newsRepository)viewModel = ViewModelProvider(this, viewModelProviderFactory).get(NewsViewModel::class.java)val article = args.articlebinding.webView.apply {webViewClient = WebViewClient()loadUrl(article.url)webViewClient = object : WebViewClient() {override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {super.onPageStarted(view, url, favicon)binding.progressBar.visibility = View.VISIBLE}override fun onPageFinished(view: WebView?, url: String?) {super.onPageFinished(view, url)binding.progressBar.visibility = View.GONE}}}binding.fab.setOnClickListener {val favouriteArticles = FavouriteArticles(article.id,article.author,article.content,article.description,article.publishedAt,article.source,article.title,article.isBookmarked,article.url,article.urlToImage)viewModel.saveArticle(favouriteArticles)Snackbar.make(view, "Article successfully saved", Snackbar.LENGTH_SHORT).show()}}}
We create a NewsViewModel
object, which calls the saveArticle()
method to save favorite articles, and the ArticleFragmentArgs
object, which is used by the navigation component to pass data between destinations in the form of type-safe key-value pairs. This ensures that the types are validated before compilation, and an error is ...