I want to achieve a layout as shown in the Android Studio preview (left). However if executed in the emulator, only the button is visible and the RecyclerView is not visible/populated (right).
The 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:layout_width="match_parent"
android:layout_height="match_parent"
style="#style/AppTheme">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/list"
android:name="com.example.app.ItemFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context=".ItemFragment"
tools:listitem="#layout/fragment_item"
android:scrollbars="vertical"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:layout_margin="#dimen/fab_margin"
android:clickable="true"
android:focusable="true"
android:src="#android:drawable/ic_input_add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
However if the RecyclerView is alone in the fragment the list is populated (but of course the action button is not showing). Code see below. And yes, my list which should be shown is not empty.
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView 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/list"
android:name="com.example.app.ItemFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context=".ItemFragment"
tools:listitem="#layout/fragment_item" >
</androidx.recyclerview.widget.RecyclerView>
I have already tried using RelativeLayout and FrameLayout, but I still get the same result. The same behavior occurs if I use e.g. a TextView instead of the action button.
--- Requested additional info ---
Adapter class (automatically generated by Android Studio, template):
class MyItemRecyclerViewAdapter(
private val mValues: List<DummyItem>,
private val mListener: OnListFragmentInteractionListener?
) : RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder>() {
private val mOnClickListener: View.OnClickListener
init {
mOnClickListener = View.OnClickListener { v ->
val item = v.tag as DummyItem
// Notify the active callbacks interface (the activity, if the fragment is attached to
// one) that an item has been selected.
mListener?.onListFragmentInteraction(item)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.fragment_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = mValues[position]
holder.mIdView.text = item.id
holder.mContentView.text = item.content
with(holder.mView) {
tag = item
setOnClickListener(mOnClickListener)
}
}
override fun getItemCount(): Int = mValues.size
inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) {
val mIdView: TextView = mView.item_number
val mContentView: TextView = mView.content
override fun toString(): String {
return super.toString() + " '" + mContentView.text + "'"
}
}
}
List fragment (automatically generated by Android Studio, template):
class ItemFragment : Fragment() {
// TODO: Customize parameters
private var columnCount = 1
private var listener: OnListFragmentInteractionListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
columnCount = it.getInt(ARG_COLUMN_COUNT)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_item_list, container, false)
// Set the adapter
if (view is RecyclerView) {
with(view) {
layoutManager = when {
columnCount <= 1 -> LinearLayoutManager(context)
else -> GridLayoutManager(context, columnCount)
}
adapter = MyItemRecyclerViewAdapter(DummyContent.ITEMS, listener)
}
}
return view
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is OnListFragmentInteractionListener) {
listener = context
} else {
throw RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener")
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
*
* See the Android Training lesson
* [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html)
* for more information.
*/
interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
fun onListFragmentInteraction(item: DummyItem?)
}
companion object {
// TODO: Customize parameter argument names
const val ARG_COLUMN_COUNT = "column-count"
// TODO: Customize parameter initialization
#JvmStatic
fun newInstance(columnCount: Int) =
ItemFragment().apply {
arguments = Bundle().apply {
putInt(ARG_COLUMN_COUNT, columnCount)
}
}
}
}
Try this for your layout
<?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"
style="#style/AppTheme"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/list"
android:name="com.example.app.ItemFragment"
android:layout_width="0dp"
android:layout_height="0dp"
android:scrollbars="vertical"
app:layoutManager="LinearLayoutManager"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:context=".ItemFragment"
tools:listitem="#layout/fragment_item" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:layout_margin="#dimen/fab_margin"
android:clickable="true"
android:focusable="true"
android:src="#android:drawable/ic_input_add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Inside ItemFragment.kt replace onCreateView with
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_item_list, container, false)
}
After that go ahead and implement onViewCreated as such
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
with(list) {
layoutManager = when {
columnCount <= 1 -> LinearLayoutManager(requireContext())
else -> GridLayoutManager(requireContext(), columnCount)
}
adapter = MyItemRecyclerViewAdapter(DummyContent.ITEMS)
}
}
This should fix your problem because the AS template is assuming that the rootview will be a RecyclerView and is treating the whole layout as such.
Related
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.
Hi I have an simple app with Bottom Navigation Activity. In Home Fragment I have a Button called Fruits. It opens a PopupWindow. In the popup is a RecyclerView with 4 Buttons(fruits names).
I want, when I press on a Button in the PopupWindow, to change the name of Button(called Fruits) form home_fragment, in whatever fruit was chosen.
HomeFragment:
class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val root: View = binding.root
return root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.Fruits.setOnClickListener {
show_popup(requireContext(), view, R.layout.fruits_popup)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
fun show_popup(c: Context, v: View, l: Int){
val popup_window = PopupWindow(c)
val inflater = layoutInflater.inflate(l, null)
val recyclerView: RecyclerView = inflater.findViewById(R.id.recycler_view)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = FruitsAdapter()
popup_window.contentView = inflater
popup_window.isFocusable = true
popup_window.isOutsideTouchable = true
popup_window.showAtLocation(v, Gravity.CENTER, 0, 0)
}
}
FruitsAdapter:
class FruitsAdapter : RecyclerView.Adapter<FruitsAdapter.FruitsViewHolder>() {
private val list = listOf<String>("Banana", "Orange", "Apple", "Watermelon")
class FruitsViewHolder(val view: View): RecyclerView.ViewHolder(view) {
val button = view.findViewById<Button>(R.id.fruit)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FruitsViewHolder {
val layout = LayoutInflater.from(parent.context).inflate(R.layout.fruit, parent, false)
return FruitsViewHolder(layout)
}
override fun onBindViewHolder(holder: FruitsViewHolder, position: Int) {
val item = list.get(position)
holder.button.text = item.toString()
}
override fun getItemCount(): Int {
return list.size
}
}
fragment_gome.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.home.HomeFragment">
<Button
android:id="#+id/Fruits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fruits"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.254" />
</androidx.constraintlayout.widget.ConstraintLayout>
fruits_popup.xml:
<?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=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycler_view"/>
</FrameLayout>
fruit.xml
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fruit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:padding="8dp" />
Try to google with keyword 'callback' bro
I have created a fragment and inside that fragment I have a recyclerview but when my fragment is loaded nothing shows and it give me this error "E/RecyclerView: No adapter attached; skipping layout". Below is the code for the adapter and fragment class, any help would be appreciated
Adapter Class:
class ViewAllRecipeAdapter(private val newList: ArrayList<Recipes>) :
RecyclerView.Adapter<ViewAllRecipeAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.view_all_recipe_item, parent, false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = newList[position]
holder.recipeName.text = currentItem.recipeName
holder.recipeDesc.text = currentItem.recipeDescription
}
override fun getItemCount(): Int {
return newList.size
}
class MyViewHolder(itemview: View) : RecyclerView.ViewHolder(itemview) {
val recipeName: TextView
val recipeDesc: TextView
init {
recipeName = itemView.findViewById<View>(R.id.recipe_name) as TextView
recipeDesc = itemView.findViewById<View>(R.id.recipe_description) as TextView
}
}
}
Fragment Class:
class ViewAllMyRecipesFragment : Fragment() {
private lateinit var recyclerview: RecyclerView
private lateinit var recipeData: ArrayList<Recipes>
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View = inflater.inflate(R.layout.fragment_view_all_my_recipes, container, false)
recipeData = dummygenerator(10)
recyclerview = view.findViewById<RecyclerView>(R.id.recycler_view_all_recipes)
recyclerview.adapter = ViewAllRecipeAdapter(recipeData)
recyclerview.layoutManager = LinearLayoutManager(view.context)
recyclerview.setHasFixedSize(true)
// Inflate the layout for this fragment
return view
}
private fun dummygenerator(size: Int) : ArrayList<Recipes>{
val list = ArrayList<Recipes>()
for(i in 0 until size) {
val drawable = when (i % 3) {
0 -> "recipeName " +i
1 -> "recipeDescription " + i
else -> "Else " +i
}
val item = Recipes("title $i", "body")
list += item
}
return list
}
}
fragment_view_all_my_recipes.xml
<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"
android:orientation="vertical"
tools:context=".ui.recipe.ViewAllMyRecipesFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view_all_recipes"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="#layout/view_all_recipe_item" />
</androidx.constraintlayout.widget.ConstraintLayout>
view_all_recipe_item.xml
<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:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/recipe_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginEnd="331dp"
android:layout_marginBottom="651dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="#tools:sample/avatars" />
<TextView
android:id="#+id/recipe_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="25dp"
android:text="TextView"
android:textStyle="bold"
android:textSize="18sp"
app:layout_constraintStart_toEndOf="#+id/recipe_image"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/recipe_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="10dp"
android:text="TextView"
app:layout_constraintStart_toEndOf="#+id/recipe_image"
app:layout_constraintTop_toBottomOf="#+id/recipe_name" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try moving all onCreateView logic to onViewCreated and
recyclerview.layoutManager = LinearLayoutManager(requireActivity())
recyclerview.adapter = ViewAllRecipeAdapter(recipeData)
because sometimes it causes problem when layoutManager is after adapter.
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.
I am brand new in Android/kotlin development. I created my very first app with a recyclerView to display the folders and files of the phone. I put the recyclerView into a segment, created my data structure and adapter. Assembled together. It works - or seems to work. But the problem is that when I try to scroll the list, the initial state remains "ther" and the list content starts to scroll. Like it was two different layers. I have no clue where to find the problem. Never heard about such a bug like this. Please give me advice, some keywords where to dig and find the solution. Thanks!
class BrowseFileFragment : Fragment() {
private lateinit var attachedCtx : Context
override fun onAttach(context: Context) {
super.onAttach(context)
this.attachedCtx = context
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View?
{
var view : View = inflater.inflate(R.layout.fragment_browse_file, container, false)
val modelFactory = FileBrowseModelFactory()
val data = modelFactory.create()
bindModelToView(data, view)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
private fun bindModelToView(data: BrowseSettings, view: View)
{
var adapter = MyFileAdapter(data.FoldersAndFiles, this.attachedCtx)
var recyclerView = view.findViewById<RecyclerView>(R.id.fileItemView)
var linearLayoutManager = LinearLayoutManager(this.attachedCtx)
recyclerView.layoutManager = linearLayoutManager
recyclerView.adapter = adapter
var folderLabel = view.findViewById<TextView>(R.id.folderName)
folderLabel.text = data.CurrentFolder
}
}
The segment layout
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BrowseFileFragment">
<TextView
android:id="#+id/folderName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/hello_first_fragment"
android:textAlignment="viewStart"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/fileItemView"
android:layout_width="match_parent"
app:layout_constrainedHeight="true"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/folderName"
app:layout_constraintStart_toStartOf="#+id/folderName"
app:layout_constraintTop_toBottomOf="#+id/folderName" />
</androidx.constraintlayout.widget.ConstraintLayout>
The list line layout
<?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:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:background="#color/cardview_shadow_start_color"
android:id="#+id/itemName"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="parent"
android:padding="5dp"
android:textSize="30dp"
android:textStyle="bold" />
</androidx.constraintlayout.widget.ConstraintLayout>
And finally my adapter:
class MyFileAdapter(private val items: List<FileItem>, private val context: Context)
: RecyclerView.Adapter<MyFileAdapter.MyViewHolder>()
{
class MyViewHolder (itemView: View) :RecyclerView.ViewHolder(itemView), View.OnClickListener {
init {
itemView.setOnClickListener(this)
}
fun bindItem(f: FileItem) {
var name: TextView = itemView.findViewById(R.id.itemName) as TextView
name.text = f.Name
}
}
override fun getItemCount() = items.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater
.from(context)
.inflate(R.layout.recyclerview_filteitem_row, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
var item = items\[position\]
holder!!.bindItem( item )
}
}
It found out that as the whole list view is saved as a segment, this segment loads "automatically" and was loaded programatically also, and the two "loads" causes this thing. :( Thanks for your time guys.