Day58 of #100DaysOfCode
Hii folks 🙌
Today I will be continuing the same pathway in which I will convert the DetailActivity to the WordListFragment.
We will start by copying the companion object to WordListFragment
.
companion object {
val LETTER = "letter"
val SEARCH_PREFIX = "https://www.google.com/search?q="
}
Then, in the LetterAdapter
, in the onClickListner()
when we perform the intent, we need to update the call to putExtra()
, replacing DetailActivity.LETTER
with WordListFragment.LETTER
.
intent.putExtra(WordListFragment.LETTER, holder.button.text.toString())
Similarly, in WordAdapter
we need to update the onClickListener()
where we navigate to the search results for the word, replacing DetailActivity.SEARCH_PREFIX
with WordListFragment.SEARCH_PREFIX
.
val queryUrl: Uri = Uri.parse("${WordListFragment.SEARCH_PREFIX}${item}")
Back in WordListFragment
, we add a binding variable of type FragmentWordListBinding?
.
private var _binding: FragmentWordListBinding? = null
We then create a get-only variable so that we can reference views without having to use ?
.
private val binding get() = _binding!!
Then we need to inflate the layout, assigning the _binding
variables and returning the root view.
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentWordListBinding.inflate(inflater, container, false)
return binding.root
}
Now we will implement onViewCreated()
.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val recyclerView = binding.recyclerView
recyclerView.layoutManager = LinearLayoutManager(requireContext())
recyclerView.adapter = WordAdapter(activity?.intent?.extras?.getString(LETTER).toString(), requireContext())
recyclerView.addItemDecoration(
DividerItemDecoration(context, DividerItemDecoration.VERTICAL)
)
}
Finally, we can reset the _binding
variable in onDestroyView()
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
With all this functionality moved into WordListFragment
, we can now delete the code from DetailActivity
. All that should be left is the onCreate()
method.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityDetailBinding.inflate(layoutInflater)
setContentView(binding.root)
}
Now that we’ve successfully migrated the functionality of DetailActivity
into WordListFragment
, we no longer need DetailActivity
. We can go ahead and delete both the DetailActivity.kt
and activity_detail.xml
as well as make a small change to the manifest. Finally, as DetailActivity
no longer exists, remove the following from AndroidManifest.xml
.
<activity
android:name=".DetailActivity"
android:parentActivityName=".MainActivity" />
Further, we will see next day…
That is all for Day58 ✅
Thanks for reading, See you tomorrow!