Android Studio 浏览器视图不显示从设备媒体商店获取的图像- Android

zyfwsgd6  于 12个月前  发布在  Android
关注(0)|答案(1)|浏览(113)

我正试图显示所有图像后,从设备库阅读,但xmlclerview是不显示任何图像。

主活动:

class MainActivity : AppCompatActivity() {
        private lateinit var imageAdapter: ImageAdapter
        private lateinit var binding: ActivityMainBinding
        private val REQUEST = 112
    
        @RequiresApi(Build.VERSION_CODES.TIRAMISU)
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = ActivityMainBinding.inflate(layoutInflater)
            setContentView(R.layout.activity_main)
            imageAdapter = ImageAdapter()
            checkPermission()
            val format = SimpleDateFormat("dd-MM-yyyy")
            val strDate = format.format(Date())
            binding.btnDate.text = strDate
            val imgList = getImagesPath(this, strDate)
            prepareRecyclerView()
            setImageList(imgList)
    
        }
    
        private fun setImageList(imgList: ArrayList<String?>) {
            imageAdapter.setImageList(imgList as ArrayList<String>)
        }
    
        fun funclick(view: View) {
            pickDateTime()
        }
    
        private fun prepareRecyclerView() {
            binding.recyclerView.apply {
                layoutManager = GridLayoutManager(context, 2, GridLayoutManager.VERTICAL, false)
                adapter = imageAdapter
            }
        }
    
    
        private fun checkPermission() {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                )
                != PackageManager.PERMISSION_GRANTED
            )
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                    REQUEST
                )
        }
    
        private fun pickDateTime() {
            val currentDateTime = Calendar.getInstance()
            val startYear = currentDateTime.get(Calendar.YEAR)
            val startMonth = currentDateTime.get(Calendar.MONTH)
            val startDay = currentDateTime.get(Calendar.DAY_OF_MONTH)
    
            DatePickerDialog(
                this,
                DatePickerDialog.OnDateSetListener { picker, year, month, day ->
                    val calendar = Calendar.getInstance()
                    calendar.set(Calendar.YEAR, picker.year)
                    calendar.set(Calendar.MONTH, picker.month)
                    calendar.set(Calendar.DATE, picker.dayOfMonth)
                    val format = SimpleDateFormat("dd-MM-yyyy")
                    val strDate = format.format(calendar.getTime())
                    val imgList: ArrayList<String?> = getImagesPath(this, strDate)
                    setImageList(imgList)
                },
                startYear,
                startMonth,
                startDay
            ).show()
        }
    
    
        fun getImagesPath(activity: Activity, strDate: String): ArrayList<String?> {
            val listOfAllImages = ArrayList<String?>()
            val cursor: Cursor?
            val column_index_folder_name: Int
            var PathOfImage: String? = null
            val uri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            val projection = arrayOf<String>(
                MediaStore.MediaColumns.DATA,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME
            )
            cursor = activity.contentResolver.query(
                uri, projection, null,
                null, null
            )
            val column_index_data: Int = cursor!!.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
            column_index_folder_name = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME)
            while (cursor.moveToNext()) {
                PathOfImage = cursor.getString(column_index_data)
                val file: File = File(PathOfImage)
                if (file.exists()) {
                    val date = file.lastModified()
                    val yourDate = Date(date)
                    val formatter: DateFormat = SimpleDateFormat("dd-MM-yyyy")
                    val formattedDate: String = formatter.format(yourDate)
                    if (strDate.equals(formattedDate)) listOfAllImages.add(PathOfImage)
                }
                // listOfAllImages.add(PathOfImage)
            }
            return listOfAllImages
        }
    }
    
    ImageAdapter:
    class ImageAdapter : RecyclerView.Adapter<ImageAdapter.ImageViewHolder>() {
        private var imgList: List<String> = ArrayList()
        // var actionMenu: (String) -> Unit = {}
    
        fun setImageList(imgCount: List<String>) {
            this.imgList = imgCount
            notifyDataSetChanged()
        }
    
    
        inner class ImageViewHolder(val binding: ImageCardBinding) :
            RecyclerView.ViewHolder(binding.root) {
            init {
                binding.imgCategory.setOnClickListener {
                    // actionMenu.invoke(categoryList[position].strCategory)
                }
            }
        }
    
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
            println("called1")
            return ImageViewHolder(ImageCardBinding.inflate(LayoutInflater.from(parent.context)))
        }
    
        override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
            println("called1")
            holder.binding.apply {
                text1.text = "sadasda"
             //   imgCategory.setImageBitmap(BitmapFactory.decodeFile(imgList[position]))
                Glide.with(holder.itemView)
                    .load(R.drawable.ic_launcher_background)
                    .centerCrop()
                    .into(imgCategory)
            }
    
        }
    
        override fun getItemCount(): Int {
            return imgList.size
        }
    
    
    }

字符串

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

            <com.google.android.material.button.MaterialButton
                android:id="@+id/btn_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="50dp"
                android:onClick="funclick"
                android:text="@string/lbl_select_date"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recycler_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
                android:layout_marginStart="@dimen/value_6"
                android:scrollbars="none"
                app:layout_constraintTop_toBottomOf="@id/btn_date" />

</androidx.constraintlayout.widget.ConstraintLayout>

image_card.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="190dp"
    android:layout_height="150dp"
    android:layout_marginTop="10dp"
    android:layout_marginEnd="@dimen/value_10"
    android:layout_marginStart="@dimen/value_10">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center">

        <androidx.cardview.widget.CardView
            android:id="@+id/cardview"
            android:layout_width="180dp"
            android:layout_height="match_parent"
            app:layout_constraintStart_toStartOf="parent"
            android:elevation="10dp"
            app:cardCornerRadius="8dp">

            <ImageView
                android:id="@+id/img_category"
                android:layout_width="180dp"
                android:layout_height="150dp"
                android:scaleType="fitCenter"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
            <TextView
                android:id="@+id/text1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="10dp"
                android:text="asdsad"
                android:layout_gravity="bottom"/>
        </androidx.cardview.widget.CardView>
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>


MainActivity正在将图像列表发送到ImageAdapter。我看到图像发送到适配器,但不知何故,DataView适配器未显示。在ImageAdapter中,onBindViewHolder,getItemCount未被调用。

wwtsj6pe

wwtsj6pe1#

您面临的问题可能与MainActivityonCreate方法中不正确的布局膨胀有关。您应该使用binding变量来设置内容视图,因为您已经使用binding膨胀了您的布局。下面是更正后的onCreate方法:

@RequiresApi(Build.VERSION_CODES.TIRAMISU)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root) // Use binding.root to set the content view
    imageAdapter = ImageAdapter()
    checkPermission()
    val format = SimpleDateFormat("dd-MM-yyyy")
    val strDate = format.format(Date())
    binding.btnDate.text = strDate
    val imgList = getImagesPath(this, strDate)
    prepareRecyclerView()
    setImageList(imgList)
}

字符串
此更改可确保Activity的内容视图正确设置为绑定对象的膨胀布局。
此外,请确保ImageAdapter与布局XML中的RecyclerView正确关联(activity_main.xml)。app:layoutManager属性应设置为"androidx.recyclerview.widget.LinearLayoutManager",正如您在布局XML中定义的那样。
如果onBindViewHoldergetItemCount方法仍然没有被调用,请确保您在prepareRecyclerView函数中将适配器设置为RecyclerView,就像您已经做的那样。如果问题仍然存在,请考虑检查setImageList方法,以确保它正确更新适配器中的数据。
如果您已经验证了这些点,但仍然面临问题,请检查logcat中的任何错误消息,这些消息可能提供有关错误原因的更多信息。

相关问题