将RecyclerView中的数据应用到MainActivity。

huangapple go评论77阅读模式
英文:

How to apply data from RecyclerView to MainActivity

问题

以下是您的翻译内容:

我有一个带有图片的水平Recyclerview。我想要当我点击Recyclerview上的图片时,设置我的MainActivity imageView 的背景。我不知道如何从Recyclerview应用到我的Mainactivity类。

这是我的MainActivity类:

class MainActivity : AppCompatActivity() {

    private lateinit var recyclerView: RecyclerView
    private var imagesUrl: ArrayList<String> = ArrayList()

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

        takeCapture.setOnClickListener(takePictureListener)

        getImagesUrl()
    }

    private fun getImagesUrl() {
        imagesUrl.apply {
            add("https://image.freepik.com/free-photo/dark-studio-background_1258-14.jpg")
            add("https://i.pinimg.com/236x/e7/f6/47/e7f647952cc3f7381d0707965e422db0.jpg")
            add("https://image.freepik.com/free-vector/abstract-dark-black-background-studio-room-with-sportlight_1035-18643.jpg")
            add("https://thumbs.dreamstime.com/z/empty-black-studio-room-dark-background-abstract-texture-product-showcase-spotlight-gallery-136762537.jpg")
        }
        initRecyclerView()
    }

    private fun initRecyclerView() {
        recyclerView = findViewById(R.id.recyclerView)
        recyclerView.apply {
            layoutManager = LinearLayoutManager(applicationContext, LinearLayoutManager.HORIZONTAL, false)
            adapter = ImageAdapter(applicationContext, imagesUrl)
        }
    }

    private val takePictureListener = View.OnClickListener {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        startActivityForResult(intent, 0)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        val bitmap = data!!.extras!!.get("data") as Bitmap
        val resized = Bitmap.createScaledBitmap(bitmap, 700, 550, true)
        imageView.setImageBitmap(resized)
    }
}

以及我的RecyclerView Adapter类:

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

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        Picasso.get().load(list[position]).into(holder.circleImageView)
    }

    override fun getItemCount(): Int = list.size

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val circleImageView : CircleImageView = itemView.circleImage
    }
}
英文:

I have horizontal Recyclerview with images. I want when I click the image on Recyclerview to set the background of my MainActivity imageView. I don't know how to apply from Recyclerview to my Mainactivity class.

This is my MainActivity class:

 class MainActivity : AppCompatActivity() {
    
        private lateinit var recyclerView: RecyclerView
        private var imagesUrl: ArrayList&lt;String&gt; = ArrayList()
        
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            takeCapture.setOnClickListener(takePictureListener)
    
            getImagesUrl()
        }
    
        private fun getImagesUrl() {
            imagesUrl.apply {
                add(&quot;https://image.freepik.com/free-photo/dark-studio-background_1258-14.jpg&quot;)
                add(&quot;https://i.pinimg.com/236x/e7/f6/47/e7f647952cc3f7381d0707965e422db0.jpg&quot;)
                add(&quot;https://image.freepik.com/free-vector/abstract-dark-black-background-studio-room-with-sportlight_1035-18643.jpg&quot;)
                add(&quot;https://thumbs.dreamstime.com/z/empty-black-studio-room-dark-background-abstract-texture-product-showcase-spotlight-gallery-136762537.jpg&quot;)
            }
            initRecyclerView()
        }
    
        private fun initRecyclerView() {
            recyclerView = findViewById(R.id.recyclerView)
            recyclerView.apply {
                layoutManager = LinearLayoutManager(applicationContext, LinearLayoutManager.HORIZONTAL, false)
                adapter = ImageAdapter(applicationContext, imagesUrl)
            }
        }
    
        private val takePictureListener = View.OnClickListener {
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            startActivityForResult(intent, 0)
        }
    
        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            super.onActivityResult(requestCode, resultCode, data)
    
            val bitmap = data!!.extras!!.get(&quot;data&quot;) as Bitmap
            val resized = Bitmap.createScaledBitmap(bitmap, 700, 550, true)
            imageView.setImageBitmap(resized)
        }

}

And my RecyclerView Adapter class

class ImageAdapter(private val context: Context, private val list: ArrayList&lt;String&gt;) : RecyclerView.Adapter&lt;ImageAdapter.ViewHolder&gt;() {

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        Picasso.get().load(list[position]).into(holder.circleImageView)
    }

    override fun getItemCount(): Int = list.size

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val circleImageView : CircleImageView = itemView.circleImage
    }
}

答案1

得分: 3

以下是您要翻译的代码部分:

这里我使用了回调方法与接口当您的RecyclerView中的任何项目被点击时您将获得一个回调您可以在活动中使用该回调进行相应的修改

您的MainActivity类将变成这样-

class MainActivity : AppCompatActivity(): ImagesAdapter.OnItemClickListener {

    private lateinit var recyclerView: RecyclerView
    private var imagesUrl: ArrayList<String> = ArrayList()
    private lateinit var imageAdapter: ImageAdapter

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

        takeCapture.setOnClickListener(takePictureListener)

        getImagesUrl()
    }

    private fun getImagesUrl() {
        imagesUrl.apply {
            add("https://image.freepik.com/free-photo/dark-studio-background_1258-14.jpg")
            add("https://i.pinimg.com/236x/e7/f6/47/e7f647952cc3f7381d0707965e422db0.jpg")
            add("https://image.freepik.com/free-vector/abstract-dark-black-background-studio-room-with-sportlight_1035-18643.jpg")
            add("https://thumbs.dreamstime.com/z/empty-black-studio-room-dark-background-abstract-texture-product-showcase-spotlight-gallery-136762537.jpg")
        }
        initRecyclerView()
    }

    private fun initRecyclerView() {
        recyclerView = findViewById(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) //您的活动的上下文
        imageAdapter = ImageAdapter(this, imagesUrl) //您的活动的上下文
        recyclerView.adapter = imageAdapter
        imageAdapter.setOnItemClickListener(this)
    }

    private val takePictureListener = View.OnClickListener {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        startActivityForResult(intent, 0)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        val bitmap = data!!.extras!!.get("data") as Bitmap
        val resized = Bitmap.createScaledBitmap(bitmap, 700, 550, true)
        imageView.setImageBitmap(resized)
    }

    override fun onItemClicked(backroundImage: String) {
        Picasso.get().load(backroundImage).into(imageView) //在这里传递您的活动类的ImageView
    }

}

而您的适配器类更改将如下所示-

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

    private lateinit var onItemClickListener: OnItemClickListener

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        Picasso.get().load(list[position]).into(holder.circleImageView)
    }

    override fun getItemCount(): Int = list.size

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val circleImageView: CircleImageView = itemView.circleImage
        itemView.setOnItemClickListener {
            if (::onItemClickListener.isInitialized)
                onItemClickListener.onItemClicked(list[adapterPosition])
        }
    }

    interface OnItemClickListener {
        fun onItemClicked(background: String)
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
        this.onItemClickListener = onItemClickListener
    }
}

希望这对您有所帮助!如果您有任何其他翻译请求,请随时提出。

英文:

Here I have used callback approach with interfaces where on the click of any item in your recyclerView you'll be getting a callback and you can do alteration accordingly with that callback in your activity.

Your MainActivity class will become something like this:-

class MainActivity : AppCompatActivity():ImagesAdapter.OnItemClickListener {
private lateinit var recyclerView: RecyclerView
private var imagesUrl: ArrayList&lt;String&gt; = ArrayList()
private lateinit var imageAdapter:ImageAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
takeCapture.setOnClickListener(takePictureListener)
getImagesUrl()
}
private fun getImagesUrl() {
imagesUrl.apply {
add(&quot;https://image.freepik.com/free-photo/dark-studio-background_1258-14.jpg&quot;)
add(&quot;https://i.pinimg.com/236x/e7/f6/47/e7f647952cc3f7381d0707965e422db0.jpg&quot;)
add(&quot;https://image.freepik.com/free-vector/abstract-dark-black-background-studio-room-with-sportlight_1035-18643.jpg&quot;)
add(&quot;https://thumbs.dreamstime.com/z/empty-black-studio-room-dark-background-abstract-texture-product-showcase-spotlight-gallery-136762537.jpg&quot;)
}
initRecyclerView()
}
private fun initRecyclerView() {
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)        //Your activity&#39;s context
imageAdapter = ImageAdapter(this, imagesUrl)        //Your activity&#39;s context
recyclerView.adapter = imageAdapter
imageAdapter.setOnItemClickListener(this)
}
private val takePictureListener = View.OnClickListener {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, 0)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val bitmap = data!!.extras!!.get(&quot;data&quot;) as Bitmap
val resized = Bitmap.createScaledBitmap(bitmap, 700, 550, true)
imageView.setImageBitmap(resized)
}
override fun onItemClicked(backroundImage:String){
Picasso.get().load(backroundImage).into(imageView)         //Here pass the image view of your activity class
}
}

And your adapter class changes will be something like this:-

class ImageAdapter(private val context: Context, private val list: ArrayList&lt;String&gt;) : RecyclerView.Adapter&lt;ImageAdapter.ViewHolder&gt;() {
private lateinit var onItemClickListener:OnItemClickListener
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.image_recycler, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
Picasso.get().load(list[position]).into(holder.circleImageView)
}
override fun getItemCount(): Int = list.size
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val circleImageView : CircleImageView = itemView.circleImage
itemView.setOnItemClickListener{
if (::onItemClickListener.isInitialized)
onItemClickListener.onItemClicked(list[adapterPosition])
}
}
interface OnItemClickListener{
fun onItemClicked(background:String)
}
fun setOnItemClickListener(onItemClickListener:OnItemClickListener){
this.onItemClickListener = onItemClickListener
}
}

答案2

得分: 0

最简单的解决方案是将对MainActivity的引用传递给ImageAdapter

// 将ImageAdapter的构造函数更改为
class ImageAdapter(
  private val context: Context, 
  private val list: ArrayList<String>,
  private val activity: MainActivity
)

MainActivity中添加一个公共方法来更改背景:

fun changeBackground(drawable: Drawable) {
  // 更改MainActivity的背景
}

然后在ImageAdapter内调用该方法:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
  ...
  activity.changeBackground()
}

您还可以考虑将ImageAdapterMainActivity解耦,并将回调函数(例如(Drawable) -> Unit)传递给ImageAdapter。在这种情况下,MainActivity将向ImageAdapter的构造函数传递一个lambda表达式,ImageAdapter将在onClickListener内部调用该lambda表达式。

英文:

The simplest solution would be to pass a reference to MainActivity into the ImageAdapter:

// Change ImageAdapter&#39;s constructor to
class ImageAdapter(
private val context: Context, 
private val list: ArrayList&lt;String&gt;,
private val activity: MainActivity
)
// In MainActivity
adapter = ImageAdapter(applicationContext, imagesUrl, this)

Add a public method to MainActivity that changes the background:

fun changeBackground(drawable: Drawable) {
// Change MainActivity&#39;s background
}

And call that method inside ImageAdapter:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
...
activity.changeBackground()
}

You might also want to decouple ImageAdapter from MainActivity and pass a callback function, e.g. (Drawable) -&gt; Unit, into ImageAdapter instead. In this case, MainActivity will pass a lambda to ImageAdapter's constructor, and ImageAdapter will call that lambda inside an onClickListener.

huangapple
  • 本文由 发表于 2020年8月3日 21:05:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63230015.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定