Fragment OnInflate never called - android-fragments

I'm trying to use the custom attributes but the onInflate method is never called.
Here is my code:
class NavigationBarFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_navigation_bar, container, false)
// get arguments
val title = requireArguments().getString(ARG_TITLE, "")
//[...]
binding = DataBindingUtil.bind(view)!!
val viewModelFactory = NavigationBarViewModelFactory(title)
viewModel = ViewModelProvider(this, viewModelFactory).get(NavigationBarViewModel::class.java)
binding.viewModel = viewModel
return view;
}
override fun onInflate(context: Context, attrs: AttributeSet, savedInstanceState: Bundle?) {
super.onInflate(context, attrs, savedInstanceState)
}
}
Thanks

Related

I don't know how to use currentItem correctly in fragments. Please help me

I use view bidning in my all fragments. and I use Fragment vinding on viewpager. the code is below
class dayspager22 : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private var _binding: FragmentDayspager22Binding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentDayspager22Binding.inflate(inflater, container, false)
val fragmentList = arrayListOf<Fragment>(
pagertest(),
days_1(),
days_2(),
days_3()
)
val adapter = ViewPagerAdapter(
fragmentList,
requireActivity().supportFragmentManager,
lifecycle
)
binding.views.adapter = adapter
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
}
and I use findViewById on my viewbinding Fragment pages
class pagertest : Fragment() {
private var _binding: FragmentPagertestBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
_binding = FragmentPagertestBinding.inflate(inflater, container, false)
binding.button.setOnClickListener{
val pager = activity?.findViewById<ViewPager2>(R.id.dayspager22)
pager?.currentItem = 1
}
return binding.root
}
}
I check 'pager' data, It's always 'null'. I tried to move setOnClickListener to onViewCreated. but It's not also worked. please help me

Put pdf files which I download from Firebase Cloud Storage to recyclerview using Kotlin

I have prepared recyclerview to show pdf files but when I try some functions to put pdfs into recyclerview they didin't show. Is any function to do this?
This is my adapter and here probably all is well
class AdapterKarty(private val fileList: ArrayList<plik>): RecyclerView.Adapter<AdapterKarty.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AdapterKarty.ViewHolder {
val a = LayoutInflater.from(parent.context).inflate(R.layout.karta_pliku,parent, false)
return ViewHolder(a);
}
override fun onBindViewHolder(holder: AdapterKarty.ViewHolder, position: Int) {
var item = fileList[position]
holder.dokument.text = item.Name
}
override fun getItemCount(): Int {
return fileList.size
}
inner class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
var dokument: TextView = itemView.tv_dokment
}
}
In list I use class plik where i declare only name because here i try put name of pdf
class plik( var Name: String?=null){
}
And here I have my main class where I try put those files to recyclerview
class Dokumenty : AppCompatActivity() {
private var stor: FirebaseStorage?=null
private var storageReference = stor?.reference
lateinit var recyclerView: RecyclerView
private lateinit var listaPlikow : ArrayList<plik>
private lateinit var myAdapter: AdapterKarty
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dokumenty)
stor = FirebaseStorage.getInstance()
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.setHasFixedSize(true)
listaPlikow = arrayListOf()
myAdapter = AdapterKarty(listaPlikow)
getFiles()
}
private fun getFiles() {
var pliki = storageReference?.child("Pliki/")
}
}

SetOnClickListener for Button within RecyclerView to access viewmodel and perform action on room database

I would like to add a "delete" button in a RecyclerView showing a list of "Users" present in a Room Database. The button should permit to delete the single user when clicking on the button. I have tried to insert a function in Myviewholder, but when I call it in OnBindViewHolder the error concerns the initialization of the mUserViewModel. Do you have any suggestion on it?
This is the adapter:
class ListAdapterUser: RecyclerView.Adapter<ListAdapterUser.MyViewHolder>() {
private var UserList = emptyList<User>()
private lateinit var mUserViewModel: UserViewModel
class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val button = itemView.findViewById<Button>(R.id.deleteoption)
fun deleteitem(item: User, viewModel: UserViewModel){
button.setOnClickListener{
viewModel.deleteUser(item)
}}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.custom_rowUser, parent, false))
}
override fun getItemCount(): Int {
return UserList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = UserList[position]
holder.itemView.textview_valueUser.text = currentItem.Uservalue.toString()
holder.deleteitem(currentItem, mUserViewModel)
}
fun setUserData(User: List<User>){
this.UserList = User
notifyDataSetChanged()
}
}
Thank you!
Solved obtaining the viewmodel initialized in the fragment passing it with setUserData function. Here the final code:
class ListAdapterUser: RecyclerView.Adapter<ListAdapterUser.MyViewHolder>() {
private var UserList = emptyList<User>()
private lateinit var mUserViewModel: UserViewModel
class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val button = itemView.findViewById<Button>(R.id.deleteoption)
fun deleteitem(item: User, viewModel: UserViewModel){
button.setOnClickListener{
viewModel.deleteUser(item)
}}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.custom_rowUser, parent, false))
}
override fun getItemCount(): Int {
return UserList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = UserList[position]
holder.itemView.textview_valueUser.text = currentItem.Uservalue.toString()
holder.deleteitem(currentItem, mUserViewModel)
}
fun setUserData(User: List<User>, viewModel: UserViewModel)){
this.UserList = User
this.mUserViewModel = viewModel
notifyDataSetChanged()
}}

how to create DialogFragment in Compose?

I am converting my app to Compose,
class BinDetailDialogFragment //private View pic;
: DialogFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return ComposeView(requireContext()).apply {
setContent {
Text(
text = "This is Recipe Fragment",
style = TextStyle(
fontSize = TextUnit.Sp(21)
)
)
}
}
}
}
when I open dialogFragment:
activity?.supportFragmentManager?.let {
BinDetailDialogFragment.newInstance().show(it, BinDetailDialogFragment.TAG)
}
it throws
java.lang.NoSuchMethodError: No virtual method setContent(Lkotlin/jvm/functions/Function0;)V in class Landroidx/compose/ui/platform/ComposeView; or its super classes (declaration of 'androidx.compose.ui.platform.ComposeView' appears in

I am unable to use searchView with multiple fragments

In my application I have two fragments Fragment Card, Fragment Note. I am using ViewPager and TabLayout to sliding between two fragments. I want to implement a search function in my application.
This is my MainActivity class in Kotlin
class MainActivity : AppCompatActivity() {
private lateinit var viewPager:ViewPager
private lateinit var tabLayout:TabLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
//toolbar.title = "Cards"
initComponent()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
val sv: SearchView = menu!!.findItem(R.id.action_bar_search).actionView as SearchView
val sm = getSystemService(Context.SEARCH_SERVICE) as SearchManager
sv.setSearchableInfo(sm.getSearchableInfo(componentName))
sv.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(p0: String?): Boolean {
//loadQuery("%"+p0+"%")
return false
}
override fun onQueryTextChange(p0: String?): Boolean {
//loadQuery("%"+p0+"%")
return false
}
})
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item != null) {
when (item.itemId) {
R.id.sort -> {
Toast.makeText(context, "sort note", Toast.LENGTH_SHORT).show()
}
R.id.settings -> {
Toast.makeText(context, "settings note", Toast.LENGTH_SHORT).show()
}
}
}
return super.onOptionsItemSelected(item)
}
private fun initComponent() {
viewPager = findViewById(R.id.view_pager)
setupViewPager(viewPager)
tabLayout = findViewById(R.id.tab_layout)
tabLayout.setupWithViewPager(viewPager)
viewPager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
changeFabIcon(position)
toolbar.title = tabLayout.getTabAt(position)!!.text.toString()
super.onPageSelected(position)
}
})
fabT.setOnClickListener {
//var text = ""
when (viewPager.currentItem) {
0 -> {
// open add new card page
startActivity(Intent(this, AddCardActivity::class.java))
//text = "Add Card"
}
1 -> {
// open add new note page
startActivity(Intent(this, AddNoteActivity::class.java))
//text = "Add note"
}
}
//Toast.makeText(applicationContext, text, Toast.LENGTH_SHORT).show()
}
}
private fun changeFabIcon(index: Int) {
fabT.hide()
Handler().postDelayed({
when(index) {
0 -> {
fabT.setImageResource(R.drawable.ic_card)
}
1 -> {
fabT.setImageResource(R.drawable.ic_note)
}
}
fabT.show()
}, 400)
}
private fun setupViewPager(view_pager: ViewPager) {
val mAdapter = ViewPagerAdapter(supportFragmentManager)
mAdapter.addFragment(FragmentCard(), "Cards")
mAdapter.addFragment(FragmentNote(), "Notes")
view_pager.adapter = mAdapter
}
internal inner class ViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager) {
private val mFragmentList = ArrayList<Fragment>()
private val mFragmentTitleList = ArrayList<String>()
override fun getItem(position: Int): Fragment {
return mFragmentList[position]
}
override fun getCount(): Int {
return mFragmentList.size
}
fun addFragment(fragment: Fragment, title: String) {
mFragmentList.add(fragment)
mFragmentTitleList.add(title)
//fragment.arguments = args
}
override fun getPageTitle(position: Int): CharSequence? {
return mFragmentTitleList[position]
}
}
}
This is my FragmentNote class in Kotlin
class FragmentNote: Fragment() {
private var listNotes = ArrayList<Note> ()
private lateinit var mRecyclerViewNote: RecyclerView
private lateinit var mAdapterNote: RecyclerViewAdapterNote
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.note_fragment, container, false)
mAdapterNote = RecyclerViewAdapterNote(context!!, listNotes, this)
mRecyclerViewNote = v.findViewById(R.id.noteRecView) as RecyclerView
mRecyclerViewNote.layoutManager = LinearLayoutManager(context)
mRecyclerViewNote.addItemDecoration(DividerItemDecoration(context, LinearLayoutManager.VERTICAL))
mRecyclerViewNote.adapter = mAdapterNote
setHasOptionsMenu(true)
NoteLoadQuery("%")
return v
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_main, menu)
super.onCreateOptionsMenu(menu, inflater)
}
private fun NoteLoadQuery(title: String) {
var dbManager = DbManagerNote(context!!)
val projections = arrayOf("ID", "Title", "Description")
val selectionArgs = arrayOf(title)
// sort by title
val cursor = dbManager.Query(projections, "ID like ?", selectionArgs, "ID")
listNotes.clear()
// ascending
if (cursor.moveToLast()) {
do {
val ID = cursor.getInt(cursor.getColumnIndex("ID"))
val Title = cursor.getString(cursor.getColumnIndex("Title"))
val Description = cursor.getString(cursor.getColumnIndex("Description"))
listNotes.add(Note(ID, Title, Description))
} while (cursor.moveToPrevious())
}
mAdapterNote.notifyDataSetChanged()
}
}
and finally this is my FragmentCard class
class FragmentCard: Fragment() {
private var listCards = ArrayList<Card>()
private lateinit var myRecyclerViewCard: RecyclerView
private lateinit var mAdapter: RecyclerViewAdapterCard
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.card_fragment, container, false)
mAdapter = RecyclerViewAdapterCard(context!!,listCards, this)
myRecyclerViewCard = v.findViewById(R.id.cardRecView) as RecyclerView
myRecyclerViewCard.layoutManager = LinearLayoutManager(context)
myRecyclerViewCard.addItemDecoration(DividerItemDecoration(context, LinearLayoutManager.VERTICAL))
myRecyclerViewCard.adapter = mAdapter
setHasOptionsMenu(true)
CardLoadQueryAscending("%")
return v
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_main, menu)
super.onCreateOptionsMenu(menu, inflater)
}
private fun CardLoadQueryAscending(title: String) {
var dbManager = DbManagerCard(context!!)
val projections = arrayOf("ID", "CardName", "CardNum")
val selectionArgs = arrayOf(title)
// sort by title
val cursor = dbManager.Query(projections, "CardName like ?", selectionArgs, "CardName")
listCards.clear()
// ascending
if (cursor.moveToFirst()) {
do {
val ID = cursor.getInt(cursor.getColumnIndex("ID"))
val CardName = cursor.getString(cursor.getColumnIndex("CardName"))
val CardNum = cursor.getString(cursor.getColumnIndex("CardNum"))
listCards.add(Card(ID, CardName, CardNum))
} while (cursor.moveToNext())
}
mAdapter.notifyDataSetChanged()
}
}
I am trying to implement my search view in MainActivity, but I am unable to do. can anyone please give me your valuable suggestions to get my problem solve. thanks in advance.
I have done this, it is quite simple.
Just make your MainActivity own the SearchView. As you already did.
Then make a simple interface
ISearchChangedListener
onTextChanged(newString: String?)
onSearchSubmitted()
Setup your BaseFragment to implement this interface.
Override the implementation in your child fragments of the BaseFragment
Then keep track of mSelectedFragment on PageChanged.
Then you simply call
mSelectedFragment?.onTextChanged(newString)
whenever the parent gets a text changed and handle appropriately.

Resources