Я пытаюсь построить представление Recycler, где каждый элемент состоит из TextClock и TextView.
Данные для представления элемента будут вводиться как ArrayList при инициализации адаптера представления Recycler.
Я нашелчто если входной размер ArrayList только один, представление будет успешно построено. Как показано на этом снимке экрана https://i.ibb.co/MskHGL7/Webp-net-resizeimage.png
Когда я увеличу данные ArrayList до 2, это приведет к ошибке при копировании ниже.
class ClockFragment : Fragment() {
val sharedPref = activity?.getSharedPreferences(
Constants().PREF_KEY_MANUAL_CLOCK,
Context.MODE_PRIVATE
)
val isAnalogshow = sharedPref?.getBoolean(Constants().PREF_KEY_MANUAL_CLOCK, false)
lateinit var view: ViewGroup
private lateinit var recyclerView: RecyclerView
private lateinit var viewAdapter: ClockRecyclerViewAdapter
private lateinit var viewManager: RecyclerView.LayoutManager
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
view = inflater.inflate(R.layout.fragment_clock, container, false) as ViewGroup
viewManager = LinearLayoutManager(this.context)
viewAdapter = ClockRecyclerViewAdapter(getData())
recyclerView = view.findViewById<RecyclerView>(R.id.clock_rv).apply {
setHasFixedSize(true)
layoutManager = viewManager
adapter = viewAdapter
}
view.clock_switch.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
sharedPref?.edit {
putBoolean(Constants().PREF_KEY_MANUAL_CLOCK, true)
commit()
}
} else {
sharedPref?.edit {
putBoolean(Constants().PREF_KEY_MANUAL_CLOCK, false)
commit()
}
}
}
return view
}
override fun onResume() {
super.onResume()
getData()
}
fun getData(): ArrayList<Clock> {
val clockList = arrayListOf<Clock>()
clockList.add(Clock(Calendar.getInstance()))
clockList.add(Clock(Calendar.getInstance()))
return clockList
}
}
Адаптер RecyclerView
class ClockRecyclerViewAdapter(private var clockList: ArrayList<Clock>?) : RecyclerView.Adapter<ClockRecyclerViewAdapter.ClockViewHolder>() {
class ClockViewHolder(val itemview: View) : RecyclerView.ViewHolder(itemview)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ClockViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_clock, parent, false)
return ClockViewHolder(view)
}
override fun onBindViewHolder(holder: ClockViewHolder, position: Int) {
val formattedDate = SimpleDateFormat("EEEE, d MMMM")
var calendar = clockList!!.get(position)!!.timezoneCalendar
holder.itemview.date_tv.text = formattedDate.format(calendar.time)
}
override fun getItemCount(): Int = clockList?.size ?: 0
fun setData(data: ArrayList<Clock>) {
clockList = data
notifyDataSetChanged()
}
}
макет элемента:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<FrameLayout
android:id="@+id/clock_frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextClock
android:id="@+id/digital_clock_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:format12Hour="hh:mm:ss a"
android:textSize="56sp"/>
<com.arbelkilani.clock.Clock
android:id="@+id/analog_clock"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="24dp"
android:visibility="gone"
app:center_inner_color="#000000"
app:clock_value_disposition="regular"
app:clock_value_step="full"
app:show_center="true"
app:show_hours_values="true"
app:show_seconds_needle="true" />
</FrameLayout>
<TextView
android:id="@+id/date_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textAppearance="?android:textAppearanceLarge"
app:layout_constraintEnd_toEndOf="@+id/clock_frame"
app:layout_constraintStart_toStartOf="@+id/clock_frame"
app:layout_constraintTop_toBottomOf="@+id/clock_frame"/>
Сообщение об ошибке Logcat:
Process: com.andreasgift.myclock, PID: 17909
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.Handler.postAtTime(java.lang.Runnable, long)' on a null object reference
at android.widget.TextClock$2.run(TextClock.java:191)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)