Android Kotlin: How to align vertically RecyclerView in fragment - android

I wanna align vertically all of items in RecyclerView like ListView but I'm confused to set them.
In other words, They are seen horizontally : https://i.stack.imgur.com/ossLb.jpg
item's image is here : https://i.stack.imgur.com/sjDws.png
Main Activity(CalendarActivity.kt) gets Fragment(HomeFragment) which gets item's information.
CalendarActivity (Main Activity)
L HomeFragment (items are shown in here)
L item (note_layout.xml)
Many solutions I've seen are Add this RecyclerView.layoutManager = LinearLayoutManager(this) in MainActivity.
Even if I added in CalendarActivity, It returns error : kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized
And In HomeFragment, I added binding.recyclerViewNotes.layoutManager = LinearLayoutManager(activity) in onCreateView, but It returns same error.
It is related to ViewBinding of course. But what I wanna say is I didn't search way with reference.
What shoud I do in this situation? I'm stuck here.
Someone help please? 🤕
CalendarActivity.kt
class CalendarActivity : AppCompatActivity() {
val TAG: String = "CalenderActivity"
//private lateinit var binding: FragmentHomeBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_calendar)
Log.d(TAG, "CalendarActivity - onCreate() called")
//binding = FragmentHomeBinding.inflate(layoutInflater)
//binding.recyclerViewNotes.layoutManager = LinearLayoutManager(this)
//setContentView(binding.root)
val navController = Navigation.findNavController(this, R.id.fragment)
NavigationUI.setupActionBarWithNavController(this, navController)
}
override fun onSupportNavigateUp(): Boolean {
Log.d(TAG, "CalendarActivity - onSupportNavigateUp() called")
return NavigationUI.navigateUp(
Navigation.findNavController(this, R.id.fragment),
null
)
}
}
HomeFragment.kt
class HomeFragment : BaseFragment() {
private lateinit var binding: FragmentHomeBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
//binding.recyclerViewNotes.layoutManager = LinearLayoutManager(activity)
binding = FragmentHomeBinding.inflate(inflater)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
binding.recyclerViewNotes.setHasFixedSize(true)
binding.recyclerViewNotes.layoutManager = StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)
launch {
context?.let {
val notes = NoteDatabase(it).getNoteDao().getAllNotes()
binding.recyclerViewNotes.adapter = NotesAdapter(notes)
}
}
binding.buttonAdd.setOnClickListener {
val action = HomeFragmentDirections.actionAddNote()
Navigation.findNavController(it).navigate(action)
}
}
}
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.HomeFragment"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view_notes"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/button_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="20dp"
android:layout_marginBottom="40dp"
android:clickable="true"
android:src="#drawable/ic_add" />
</LinearLayout>
note_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:gravity="center_vertical">
<TextView
android:id="#+id/text_date"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_weight="2"
android:text="2021/01/01"
android:textColor="#111111"
android:textSize="12sp" />
<TextView
android:id="#+id/text_view_title"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4"
android:layout_marginTop="5dp"
android:text="Title"
android:textStyle="bold"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Headline" />
</LinearLayout>
If you need more detailed information, please comment! thank you!

You have already assigned a LinearLayoutManager in your XML, and that's the type that looks like ListView.
So just delete this line where you are changing it to a staggered grid, which is not what you want:
binding.recyclerViewNotes.layoutManager = StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)

Change your code to this
binding.recyclerViewNotes.layoutManager = StaggeredGridLayoutManager(1,
StaggeredGridLayoutManager.VERTICAL)
or You can also use LinearLayoutManager instead of StaggeredGridLayoutManager
binding.recyclerViewNotes.layoutManager = new LinearLayoutManager(this);

Related

ViewPager2 misses the tablayout indicator

The following problem occurred with me after migration from viewPager to viewPager2 - when I open my app, the tablyout indicator is missing by default. But if you make some swiping, the indicator will appears! Looks weird, because I made everything correct. There are my simplified Kotlin-code:
class ScheduleWeekFragment : ScheduleBaseFragment<ScheduleWeekViewModel>(ScheduleWeekViewModel::class) {
private val viewBinding by viewBinding(FragmentWeekBinding::bind)
private var titles: Array<String>? = null
// listeners
private val viewPagerListener = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
viewModel.updateDayTitle(position)
}
}
// observers
private val selectedDayObserver = Observer<Int> {
viewBinding.viewPager2.currentItem = it
}
// lifecycle
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
titles = context?.resources?.getStringArray(R.array.schedule_fragment_day_abbreviations)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_week, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewBinding.viewPager2.adapter = ScheduleViewPagerAdapter(this)
viewBinding.viewPager2.setPageTransformer(ZoomOutPageTransformer)
TabLayoutMediator(viewBinding.tabLayout, viewBinding.viewPager2) { tab, position ->
tab.text = titles?.getOrNull(position)
}.attach()
// observers
viewModel.viewPagerPosition.observe(viewLifecycleOwner, selectedDayObserver)
// listeners
viewBinding.viewPager2.registerOnPageChangeCallback(viewPagerListener)
}
override fun onDestroyView() {
viewBinding.viewPager2.unregisterOnPageChangeCallback(viewPagerListener)
super.onDestroyView()
}
}
And there is my simplified xml-code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragmentWeek"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
style="#style/TabLayout1"
android:layout_width="match_parent"
android:layout_height="40dp"
android:verticalScrollbarPosition="left"
app:layout_constraintEnd_toEndOf="#+id/viewPager2"
app:layout_constraintStart_toStartOf="#+id/viewPager2"
app:layout_constraintTop_toBottomOf="#+id/scheduleToolbar"
app:tabGravity="start"
app:tabMode="scrollable"
android:background="#color/white"
tools:ignore="SpeakableTextPresentCheck" />
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/viewPager2"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tabLayout"
tools:ignore="SpeakableTextPresentCheck" />
</androidx.constraintlayout.widget.ConstraintLayout>
The problem was inside my observer:
private val selectedDayObserver = Observer<Int> {
// viewBinding.viewPager2.currentItem = it // wrong!
viewBinding.viewPager2.setCurrentItem(it, false) // correct!
}
I didn't find why in the official docs, but difference exists: the first variant works good with viewpager1, but for viewpager2, be careful and use the second complex variant.

move Constraint Layout programmatically

I want to move a ConstraintLayout programmatically. I looked through some solutions on stack overflow but they didn't work for me.
There are two ConstraintLayouts placed vertically. When the code goes into else if("android.permission.CAMERA" in permissionList.toString(), the above constraint layout (layoutLocation) will be invisible and the below constraint layout (layoutCamera) will come up and take its position. I mark where I should use declare it with 'want to use here'.
Code (apology to not ba able to post the whole code due to patent reason)
class SplashFragment : Fragment() {
private lateinit var mContext: MainActivity
private lateinit var binding : FragmentSplashBinding
private val viewModel : SplashViewModel by inject()
private val getPermissionUseCase : GetPermissionUseCase by inject()
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context as MainActivity
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_splash, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.viewModel = viewModel
binding.lifecycleOwner = viewLifecycleOwner
}
private fun actionApplicationSetting(permissionList : List<String>) {
val layoutInflater = LayoutInflater.from(context)
val view = layoutInflater.inflate(R.layout.dialog_splash, null)
val alertDialog = AlertDialog.Builder(requireContext(), R.style.CustomAlertDialog).setView(view).create()
val layoutLocation : ConstraintLayout = view.findViewById(R.id.layout_box_location)
val layoutCamera : ConstraintLayout = view.findViewById(R.id.layout_box_camera)
for(permission in permissionList) {
if("android.permission.CAMERA" in permissionList.toString() && "android.permission.ACCESS_COARSE_LOCATION" in permissionList.toString()) {
layoutLocation.background = AppCompatResources.getDrawable(mContext, R.drawable.auth_level_blue)
layoutCamera.background = AppCompatResources.getDrawable(mContext, R.drawable.auth_level_blue)
}else if("android.permission.ACCESS_COARSE_LOCATION" in permissionList.toString()) {
layoutLocation.background = AppCompatResources.getDrawable(mContext, R.drawable.auth_level_blue)
}else if("android.permission.CAMERA" in permissionList.toString()) {
layoutLocation.visibility = View.INVISIBLE
// want to use here
}
}
alertDialog.show()
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/layout_main"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_marginStart="70dp"
android:layout_marginBottom="10dp"
app:layout_constraintBottom_toBottomOf="#+id/layout_wrapper"
app:layout_constraintEnd_toEndOf="#+id/layout_wrapper"
app:layout_constraintStart_toStartOf="#+id/layout_wrapper">
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/layout_wrapper"
android:layout_width="match_parent"
android:layout_height="180dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/layout_box_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/layout_box_camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/layout_box_location" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Instead of layoutLocation.visibility = View.INVISIBLE try layoutLocation.visibility = View.GONE

Implementing Viewpager2 in a fragment with Recycler view

I'm trying to implement viewpager2 in a fragment which shows a list of notes with Recycler View. I tried different solutions but I'm unable to figure it out.
Here is my fragment_notes_list.xml :
<androidx.recyclerview.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/notes_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
list_item_notes.xml used to display recycler view viewholder:
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_pertanyaan"
android:layout_width="match_parent"
android:layout_height="96dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="12dp"
android:layout_marginRight="16dp"
android:clickable="true"
android:foreground="?selectableItemBackground"
card_view:cardBackgroundColor="#595959"
card_view:cardCornerRadius="8dp"
card_view:contentPadding="10dp">
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/notes_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:text="Title"
android:textColor="#color/white"
app:layout_constraintBottom_toTopOf="#+id/notes_body"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />
<TextView
android:id="#+id/notes_body"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/notes_title" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
Relevant snippets from fragment class NotesListFragment.kt :
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_notes_list, container, false)
notesRecyclerView =
view.findViewById(R.id.notes_recycler_view) as RecyclerView
registerForContextMenu(notesRecyclerView)
notesRecyclerView.layoutManager = LinearLayoutManager(context)
notesRecyclerView.adapter = adapter
return view
}
private inner class ScreenSlidePagerAdapter(fa: Fragment) : FragmentStateAdapter(fa) {
override fun getItemCount(): Int = NUM_PAGES
override fun createFragment(position: Int): Fragment {
return if (position == 0) {
NotesListFragment()
} else {
CalenderFragment()
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
notesListViewModel.notesListLiveData.observe(
viewLifecycleOwner,
Observer { notes ->
notes?.let {
Log.i(TAG, "got notes")
updateUI(notes)
}
})
}
private inner class NotesAdapter(var notes: List<Notes>) : RecyclerView.Adapter<NotesHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotesHolder {
val view = layoutInflater.inflate(R.layout.list_item_notes, parent, false)
/* viewPager = view.findViewById(R.id.pager)
val pagerAdapter = ScreenSlidePagerAdapter(this#NotesListFragment)
viewPager.adapter = pagerAdapter */
return NotesHolder(view)
}
override fun getItemCount() = notes.size
override fun onBindViewHolder(holder: NotesHolder, position: Int) {
val note = notes[position]
holder.bind(note)
}
}
I'm confused should I add ViewPager2 with FrameLayout in list_item_notes.xml?
But then how can I implement ScreenSliderPagerAdapter for it?
I assume you would like to have 2 fragments: list and calendar and thats why you need to implement ViewPager2. Your NotesListFragment looks good. You have recyclerview with notes there, but what you want now is to provide list of NotesListFragment and CalendarFragment which will be scrollable in left/right direction. First, extract ScreenSlidePagerAdapter outside of your fragment code. Next you have to add ViewPager2 to your parent activity/fragment
<androidx.viewpager2.widget.ViewPager2
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
And then in your parent activity/fragment pair it with adapter like this way:
val viewPager = findViewById(R.id.pager)
val pagerAdapter = ScreenSlidePagerAdapter(this)
viewPager.adapter = pagerAdapter
You can read more about this in official docs: https://developer.android.com/training/animation/screen-slide-2
I had tried implementing ViewPager in Main Activity earlier also. But this way i cannot close viewpager fragments since they are always visible. How do I get around this?
here is my main activity after the changes you suggested:
class MainActivity : AppCompatActivity(),
NotesListFragment.Callbacks {
private lateinit var viewPager: ViewPager2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewPager = findViewById(R.id.pager)
val pagerAdapter = ScreenSlidePagerAdapter(this)
viewPager.adapter = pagerAdapter
}
override fun onNotesSelected(notesId: UUID) {
val fragment = NotesFragment.newInstance(notesId)
supportFragmentManager
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit()
}
fun onNotesDeleted(notes: Notes) {
val fragment = NotesListFragment()
supportFragmentManager
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit()
Toast.makeText(this, "Note Deleted", Toast.LENGTH_SHORT).show()
}
mainactivity.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager2.widget.ViewPager2
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/pager"/>
</FrameLayout>
here are some screenshots,
https://drive.google.com/drive/folders/13ITZqcaeDeydCe0tW2Iu7VoSGSZnrlkg?usp=sharing
Solved the problem.
Since, I was unable to add Viewpager with recycler view of NotesListFragment, I made another Parent Fragment with viewpager and put NotesListFragment inside it.

setOnClickListener doesn't work using Fragment

I'm trying to make a simple button that changes the fragment, it doesn't give any error, it just doesn't work.
XML code:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.follow.FollowFragment">
<ImageView
android:id="#+id/imageView4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="background"
android:scaleType="fitXY"
android:src="#drawable/background" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<Button
android:id="#+id/loginButton"
android:layout_width="250dp"
android:layout_height="60dp"
android:layout_marginTop="50dp"
android:backgroundTint="#color/btn_col"
android:text="Log In" />
</LinearLayout>
</FrameLayout>
Fragment code:
class FollowFragment : Fragment() {
companion object {
fun newInstance() = FollowFragment()
}
private lateinit var viewModel: FollowViewModel
private lateinit var loginButton: Button
private lateinit var viewFollow: View
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_follow, container, false)
viewFollow = root
loginButton = viewFollow.findViewById(R.id.loginButton)
var loginFragment = LoginFragment()
println("Hello :(")
loginButton.setOnClickListener {
println("Hello :)")
//parentFragmentManager.beginTransaction().replace(R.id.nav_host_fragment, loginFragment).commit()
}
return inflater.inflate(R.layout.fragment_follow, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this).get(FollowViewModel::class.java)
// TODO: Use the ViewModel
}
}
Only the sad hello is printed, it seems to recognize the button, but the listener don't work. The app has a bottom navigation bar, and the screens are fragments.
By returning inflater.inflate(R.layout.fragment_follow, ...) you're inflating a second layout to be used for your fragment instead of the one that you're using to set the listener.
You should be returning root.

Trouble with Recyclerview. recyclerview.xml must no be null

i have the xml with recyclerview, id = list_chat
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.chats.ChatsFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/list_chat"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
my Fragment where will be recyclerview with function uploadList which put data in my array for recyclerView
class ChatsFragment : Fragment() {
var list: MutableList<Chat> = ArrayList()
lateinit var adapter: ChatListAdapter
lateinit var manager: RecyclerView.LayoutManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
uploadList()
Log.e("TAG", list.toString())
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View = inflater.inflate(R.layout.fragment_chats, container, false)
uploadList()
manager = LinearLayoutManager(activity)
list_chat.layoutManager = manager
adapter = ChatListAdapter(list)
list_chat.adapter = adapter
return view
}
private fun uploadList(){
list.add(Chat("11111", "11111"))
list.add(Chat("11222221", "133311"))
list.add(Chat("1122221", "114444411"))
list.add(Chat("112222211", "5555555"))
}
}
xml with item for list. ImageView is no matter for now. Need only two textView
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:id="#+id/item_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/chatImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginStart="5sp">
<TextView
android:id="#+id/nameChat"
android:text="2222222222222"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/infoChat"
android:text="11111111"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
</layout>
and my custom Adapter
class ChatListAdapter(private val myDataset: MutableList<Chat>) :RecyclerView.Adapter<ChatListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
.inflate(R.layout.item_list, parent, false)
return ViewHolder(layoutInflater)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(myDataset[position])
}
override fun getItemCount() = myDataset.size
class ViewHolder(v: View) : RecyclerView.ViewHolder(v){
private val nameChat: TextView = itemView.findViewById(R.id.nameChat)
private val infoChat: TextView = itemView.findViewById(R.id.infoChat)
fun bind(chat: Chat){
nameChat.text = chat.name
infoChat.text = chat.info
}
}
}
and i catch java.lang.IllegalStateException: list_chat must not be null here list_chat.layoutManager = manager
help me with it, i have list_chat only in fragment_chats, so it is right recyclerview.
Because help me pls, I dont know what is the problem
Initialize layout manager and adapter in onViewCreated() Method
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
uploadList()
manager = LinearLayoutManager(activity)
list_chat.layoutManager = manager
adapter = ChatListAdapter(list)
list_chat.adapter = adapter
})
Are you using kotlinx.android.synthetic to find your views? If so, these are not valid until after onCreateView() returns, and so you cannot use them within onCreateView().
Move your code to onViewCreated(), or switch to manually calling view.findViewById() from inside onCreateView().
Approach 1 :
Create a recyclerview object :
val rv = view.findViewById(your rv id)
and assign the layout manager and adapter to it.
Approach 2 :
In your layout file, in recyclerview add this line :
<androidx.recyclerview.widget.RecyclerView
<!-- your default lines -->
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
/>
and assign the adapter in onViewCreated method.

Categories

Resources