【问题标题】:How to add elements to a RecyclerView permanently with a button如何使用按钮将元素永久添加到 RecyclerView
【发布时间】:2021-03-10 14:28:57
【问题描述】:

我正在制作一个应用程序,其中有一个 RecyclerView,其中包含一些在创建应用程序后立即添加的固定元素。

我想要做的是,当按下Button 时,一个元素被添加到RecyclerView 中,当关闭它并再次启动它时,这个新元素仍然存在。

除此之外,我使用IndicatorView 滚动查看recyclerview 的元素。当我使用 Button 添加一些元素时,发生在我身上的问题是创建了新元素,RecyclerView 的大小增加了,但 IndicatorView 没有增加,我无法滚动查看添加的新元素,除此之外,当重新启动应用程序时,这些通过按钮添加的新元素会自行删除。

RecyclerView 添加新元素时如何增加IndicatorView 的大小?

如何在Button 上使用 onClick 将元素永久添加到 RecyclerView?

我的代码:

MainActivity.kt:

    class MainActivity : AppCompatActivity() {

    private lateinit var viewPager: ViewPager
    private lateinit var pagerAdapter: PageAdapter
    private val animalList = arrayListOf<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        animalList.add("1")
        animalList.add("2")
        animalList.add("3")
        animalList.add("4")
        animalList.add("5")
        animalList.add("6")
        animalList.add("7")
        animalList.add("8")
        animalList.add("9")
        animalList.add("10")
        animalList.add("11")
        animalList.add("12")
        animalList.add("13")
        animalList.add("14")
        animalList.add("15")
        animalList.add("16")
        animalList.add("17")


        var size = animalList.size / 4
        if ((animalList.size % 4 ) > 0)
            size += 1

        pagerAdapter = PageAdapter(supportFragmentManager, size, animalList)

        ADDbutton.setOnClickListener {

            animalList.add("lol")
            animalList.add("añadido jaja")
            Log.i("AAA","Added: "+ animalList +" SIZE: " + animalList.size)
            pagerAdapter.notifyDataSetChanged()
        }
        viewPager = findViewById(R.id.view_pager)

        pagerAdapter = PageAdapter(supportFragmentManager, size, animalList)
        viewPager.adapter = pagerAdapter

    }

}

ItemFragment.kt:

class ItemFragment : Fragment() {

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

    // Creates the view controlled by the fragment
    val view = inflater.inflate(R.layout.page, container, false)
    val recycler = view.findViewById<RecyclerView>(R.id.recycler)

    // Retrieve and display the movie data from the Bundle
    val args = arguments
    recycler.layoutManager = GridLayoutManager(activity,2,GridLayoutManager.VERTICAL,false)
    recycler.adapter = ItemAdapter(args?.getStringArrayList("items")!!, this.activity!!)

    return view
  }
  companion object {

    fun newInstance(items: ArrayList<String>): ItemFragment {

      val args = Bundle()
      args.putStringArrayList("items", items)

      val fragment = ItemFragment()
      fragment.arguments = args
      return fragment
    }
  }
}

PageAdapter.kt:

    class PageAdapter(fragmentManager: FragmentManager, private val size: Int, private val items: ArrayList<String>) :
    FragmentStatePagerAdapter(fragmentManager) {

    override fun getItem(position: Int): Fragment {
        val firstItem = ((position + 1) * 4) - 3
        val lastItem = ((position + 1) * 4)
        val itemSet = arrayListOf<String>()
        for (i in firstItem..lastItem) {
            if (i <= items.size)
                itemSet.add(items[i - 1])
        }
        return ItemFragment.newInstance(itemSet)
    }

    override fun getCount(): Int {
        return size
    }
}

ItemAdapter.kt:

    class ItemAdapter(private val items: ArrayList<String>, private val context: Context) : RecyclerView.Adapter<ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(context).inflate(R.layout.item, parent, false))
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder?.title?.text = items.get(position)
    }

    override fun getItemCount(): Int {
        return items.size
    }
}

class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    val title: TextView = view.title_view
    val item: RelativeLayout = view.item_view

}

布局:

activity_main.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:attrs="http://schemas.android.com/tools"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginBottom="32dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline2">

    </androidx.viewpager.widget.ViewPager>

    <com.rd.PageIndicatorView
        android:id="@+id/pageIndicatorView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view_pager"
        app:piv_animationType="worm"
        app:piv_dynamicCount="true"
        app:piv_interactiveAnimation="true"
        app:piv_radius="8dp"
        app:piv_selectedColor="#000000"
        app:piv_unselectedColor="#999999"
        app:piv_viewPager="@id/view_pager"
        attrs:piv_padding="8dp" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_begin="251dp"
        app:layout_constraintTop_toTopOf="parent" />
    
    <Button
        android:id="@+id/ADDbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toTopOf="@+id/view_pager"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/item_view"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_margin="10dp"
    android:background="@color/teal_700">

    <TextView
        android:id="@+id/title_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:textColor="@android:color/white"
        android:textSize="18sp"
        android:textStyle="bold" />
</RelativeLayout>

page.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:id="@+id/recycler"
        android:layout_height="match_parent"/>

【问题讨论】:

    标签: android android-studio kotlin android-recyclerview


    【解决方案1】:

    有两个问题。

    1. 您需要了解Difference between persistent and non-persistent data。 现在您只在内存中创建列表。您还需要将数据存储在某处。最合适的位置是数据库、文件或 Web 后端。

    2. ADDbutton ClickListener 中,您正在向animalList 添加一个项目。但是您没有在PageAdapter 中设置此更新列表。最简单的方法是在PagerAdapter 的构造函数中将items 参数设为public var

    class PageAdapter(
        fragmentManager: FragmentManager,
        private val size: Int,
        public var items: ArrayList<String>) : FragmentStatePagerAdapter(fragmentManager) {
    
    }
    

    更新后的点击监听器将如下所示:

    ADDbutton.setOnClickListener {
    
        animalList.add("lol")
        animalList.add("añadido jaja")
        Log.i("AAA","Added: "+ animalList +" SIZE: " + animalList.size)
        pagerAdapter.items = animalList
        pagerAdapter.notifyDataSetChanged()
    }
    

    此外,大小是固定的。您在构造函数中传递参数并在 getCount 方法中使用它:

    override fun getCount(): Int {
        return size
    }
    

    相反,getCount 应根据当前的 items.size 值计算项目计数。

    【讨论】:

    • 这是IndicatorView最后一页的主屏(gyazo.com/a915623db6e00724a27fc01540c5d79c),IndicatorView每一页的页面都是2x2的。如果我现在添加 5 个新元素,IndicatorView 应该再创建一个页面(或屏幕底部的点)并让我滚动到它并查看新元素,但不会创建新页面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 2015-04-13
    • 1970-01-01
    • 2016-12-13
    相关资源
    最近更新 更多