返回在RecyclerView中点击的正确项目位置到另一个活动中。

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

Return the correct item position clicked in RecyclerView to another activity

问题

以下是您提供的代码的中文翻译:

主类 ListeMeuble3DActivity.kt 代码:

class ListeMeuble3DActivity : AppCompatActivity() {
    var listMeubles = mutableListOf<Meuble>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_liste_meuble3_d)
        listMeubles = generateList()
        buildRecyclerView()
    }

    private fun generateList(): MutableList<Meuble> {
        val list = ArrayList<Meuble>()

        // 添加 Meuble 对象(名称,价格,库存)
        val meuble = Meuble(R.drawable.fauteilgris, "Gris", "25000da", 1)
        val meuble1 = Meuble(R.drawable.fauteuille1, "", "1000d&", 1)
        val meuble2 = Meuble(R.drawable.burau, "Bureau", "25000da", 1)
        list.add(meuble)
        list.add(meuble1)
        list.add(meuble2)

        return list
    }

    fun buildRecyclerView() {
        mon_recycler.setHasFixedSize(true)
        mon_recycler.layoutManager = LinearLayoutManager(this)

        mon_recycler.adapter = MeubleAdapter(listMeubles.toTypedArray()) {
            val intent3 = Intent(this, SceneformeActivity::class.java)
            intent3.putExtra("image_url", it)
            startActivity(intent3)
        }
    }
}

适配器类 MeubleAdapter.kt 代码:

class MeubleAdapter(private val exampleList: Array<Meuble>, val listener: (Meuble) -> Unit) :
    RecyclerView.Adapter<MeubleAdapter.ExampleViewHolder>() {

    // ...(省略其他方法)

    class ExampleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(meuble: Meuble, listener: (Meuble) -> Unit) = with(itemView) {
            android.util.Log.i("XXXX", "FCT Bind ")
            setOnClickListener { listener(meuble) }
        }

        // ...(省略其他视图绑定)
    }
}

SceneFormeActivity.java 中获取项目位置的函数:

private void initializeGallery() {
    int imageUrl = getIntent().getIntExtra("image_url", 0); // 在这里,每次都返回 1
    LinearLayout gallery = findViewById(R.id.gallery_layout);
    int obj = imageUrl;
    switch (obj) {
        case 0: {
            ImageView andy = new ImageView(this);
            andy.setImageResource(R.drawable.fauteilgris);
            andy.setContentDescription("fauteuil Crème");
            andy.setOnClickListener(view -> addObject(Uri.parse("foteuil.sfb")));
            gallery.addView(andy);
        }
        // ...(省略其他情况)
    }
}

请注意,您的代码中有一些 HTML 转义字符,我已经将它们转换为适当的文本。如果您需要进一步的帮助,请随时问我。

英文:

I'm struggling with this problem for weeks and i always get (1) returned from RecyclerView

  • i want to return the right item position clicked to SceneFormeActivity to be able to chose the correct object, but i'm getting the same "1" everytime so the same Case1'Object informations

my main class.kt code :

class ListeMeuble3DActivity : AppCompatActivity(),{
    var listMeubles = mutableListOf&lt;Meuble&gt;()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_liste_meuble3_d)
         listMeubles = generateList()
        buildRecyclerView()
    }

    private fun generateList(): MutableList&lt;Meuble&gt;{

        val list = ArrayList&lt;Meuble&gt;()

           // to Add an Object Meuble(nom,prix,stock)

            val meuble = Meuble(R.drawable.fauteilgris, &quot;Gris&quot;,&quot;25000da&quot;,1)
            val meuble1 = Meuble(R.drawable.fauteuille1, &quot;&quot;,&quot;1000d&amp;&quot;,1)
            val meuble2 = Meuble(R.drawable.burau, &quot;Bureau&quot;,&quot;25000da&quot;,1)
            list.add(meuble)
            list.add(meuble1)
            list.add(meuble2)

        return list
    }

    fun buildRecyclerView() {
        mon_recycler.setHasFixedSize(true)
        //mon_recycler.setAdapter(mAdapter)
        mon_recycler.layoutManager = LinearLayoutManager(this)

        mon_recycler.adapter = MeubleAdapter(listMeubles.toTypedArray())
        {
            val intent3 = Intent(this, SceneformeActivity::class.java)
            intent3.putExtra(&quot;image_url&quot;,1)
            startActivity(intent3)
        }
     }
 }

My Adapter Class .kt:

class MeubleAdapter(private val exampleList: Array&lt;Meuble&gt;,val listener: (Meuble)-&gt; Unit) :
    RecyclerView.Adapter&lt;MeubleAdapter.ExampleViewHolder&gt;() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.meuble_item,
            parent, false)
        return ExampleViewHolder(itemView)
    }
    override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {
        val currentItem = exampleList[position]
        holder.imageView.setImageResource(currentItem.imageResource)
        holder.textViewNomMeuble.text = currentItem.nom
        holder.textViewPrix.text = currentItem.prix
        holder.textViewStock.text = currentItem.stock.toString()

        holder.bind(exampleList[position],listener)
    }

    override fun getItemCount() = exampleList.size


    class ExampleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(meuble:Meuble,listener: (Meuble) -&gt; Unit)= with(itemView)
        {
            android.util.Log.i(&quot;XXXX&quot;,&quot;FCT Bind &quot;)
            setOnClickListener{(listener(meuble))}
        }

        val imageView: ImageView = itemView.image_view
        val textViewNomMeuble: TextView = itemView.nomMeuble
        val textViewStock: TextView = itemView.stock
        val textViewPrix: TextView = itemView.prix

    }
}

My function in SceneFormeActivity.java where im supposed to get the item position

private void initializeGallery() {
        int imageUrl = getIntent().getIntExtra(&quot;image_url&quot;,0); // here, everytime it return 1
        LinearLayout gallery = findViewById(R.id.gallery_layout);
        int obj =imageUrl;
        switch (obj) {
            case 0: {
                ImageView andy = new ImageView(this);
                andy.setImageResource(R.drawable.fauteilgris);
                andy.setContentDescription(&quot;fauteuil Cr&#233;me&quot;);
                andy.setOnClickListener(view -&gt;{addObject(Uri.parse(&quot;foteuil.sfb&quot;));});
                gallery.addView(andy);

            }
            break;
            case 1: {
                ImageView andy = new ImageView(this);
                andy.setImageResource(R.drawable.banc);
                andy.setContentDescription(&quot;banc ext&#233;rieur&quot;);
                andy.setOnClickListener(view -&gt;{addObject(Uri.parse(&quot;Bench.sfb&quot;));});
                gallery.addView(andy);

            }
            break;
            case 2 : {
                ImageView andy = new ImageView(this);
                andy.setImageResource(R.drawable.burau);
                andy.setContentDescription(&quot;bureau&quot;);
                andy.setOnClickListener(view -&gt;{addObject(Uri.parse(&quot;bureau.sfb&quot;));});
                gallery.addView(andy);

            }
            break;
            case 3 : {
                ImageView andy = new ImageView(this);
                andy.setImageResource(R.drawable.fauteuille3);
                andy.setContentDescription(&quot;Fauteuil une place&quot;);
                andy.setOnClickListener(view -&gt;{addObject(Uri.parse(&quot;ff.sfb&quot;));});
                gallery.addView(andy);

            }
            break;
            default:Toast.makeText(getApplicationContext(),&quot;Nothing&quot;,Toast.LENGTH_SHORT).show();

                break;

        }
    }

答案1

得分: 0

以下是您要翻译的部分:

如果您真正需要的只是项目的位置,那么根本不需要在单击时发送Meuble。在您的适配器中将onBindViewHolder更改为:

override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {
    val currentItem = exampleList[position]
    holder.imageView.setImageResource(currentItem.imageResource)
    holder.textViewNomMeuble.text = currentItem.nom
    holder.textViewPrix.text = currentItem.prix
    holder.textViewStock.text = currentItem.stock.toString()

    holder.bind(position, listener)
}

设置您的适配器现在应该如下所示:

mon_recycler.adapter = MeubleAdapter(listMeubles.toTypedArray()) { position ->
    val intent3 = Intent(this, SceneformeActivity::class.java)
    intent3.putExtra("image_url", position)
    startActivity(intent3)
}

编辑:扩展有关适配器使用的说明:

最初,您将两个内容传递给您的Recyclerview适配器 -

  1. Meuble列表(无需将其转换为TypedArray)
  2. 在列表中项目单击时将执行的lambda

考虑下面的重构代码,带有我的内联注释。请注意 - 我不清楚您为什么要发送位置(假设只是为了测试?),所以我假设对象中有某种图像URL要发送。我展示了如何访问它。

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_liste_meuble3_d)
    listMeubles = generateList()
    buildRecyclerView()
}

private fun generateList(): MutableList<Meuble> {
    val list = mutableListOf<Meuble>()

    // 添加Meuble对象(nom,prix,stock)

    val meuble = Meuble(R.drawable.fauteilgris, "Gris", "25000da", 1)
    val meuble1 = Meuble(R.drawable.fauteuille1, "", "1000d&", 1)
    val meuble2 = Meuble(R.drawable.burau, "Bureau", "25000da", 1)
    list.add(meuble)
    list.add(meuble1)
    list.add(meuble2)

    return list
}

fun buildRecyclerView() {
    mon_recycler.setHasFixedSize(true)
    mon_recycler.layoutManager = LinearLayoutManager(this)

    // 注意:这里的lambda隐含地传递了一个Meuble类型的项目。我们在这里命名了它,但也可以使用"it"。
    mon_recycler.adapter = MeubleAdapter(listMeubles) { item ->
        val intent3 = Intent(this, SceneformeActivity::class.java)
        intent3.putExtra("image_url", item.imageUrl)
        startActivity(intent3)
    }
}

我的适配器类.kt:

class MeubleAdapter(private val exampleList: List<Meuble>, val listener: (Meuble) -> Unit) :
    RecyclerView.Adapter<MeubleAdapter.ExampleViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.meuble_item,
            parent, false)
        return ExampleViewHolder(itemView)
    }
    override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {
        val currentItem = exampleList[position]
        holder.imageView.setImageResource(currentItem.imageResource)
        holder.textViewNomMeuble.text = currentItem.nom
        holder.textViewPrix.text = currentItem.prix
        holder.textViewStock.text = currentItem.stock.toString()

        holder.bind(exampleList[position], listener)
    }

    override fun getItemCount() = exampleList.size

    class ExampleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(meuble: Meuble, listener: (Meuble) -> Unit) = with(itemView) {
            android.util.Log.i("XXXX", "FCT Bind ")
            setOnClickListener { listener(meuble) }
        }

        val imageView: ImageView = itemView.image_view
        val textViewNomMeuble: TextView = itemView.nomMeuble
        val textViewStock: TextView = itemView.stock
        val textViewPrix: TextView = itemView.prix
    }
}
英文:

If all you really want is the position of the item then you don't need to send the Meuble on click at all. In your adapter change onBindViewHolder to:

override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {
        val currentItem = exampleList[position]
        holder.imageView.setImageResource(currentItem.imageResource)
        holder.textViewNomMeuble.text = currentItem.nom
        holder.textViewPrix.text = currentItem.prix
        holder.textViewStock.text = currentItem.stock.toString()

        holder.bind(position,listener)
    }

Setting your adapter should now look like this:

 mon_recycler.adapter = MeubleAdapter(listMeubles.toTypedArray()){ position -&gt;
            val intent3 = Intent(this, SceneformeActivity::class.java)
            intent3.putExtra(&quot;image_url&quot;, position)
            startActivity(intent3)
        }

Edit: Expanding on the adapter usage:

Originally, you are passing two things to your Recyclerview Adapter -

  1. The list of Meuble (There is no need to convert this to a TypedArray
  2. The lambda that will act on the click of an item in the list

Consider the refactored code below with my inline comments. Note - it's not clear to me why you are sending position (assuming just to test?) So instead I'm assuming there is some imageURL in the object that you wish to send. I show below how you'd access that.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_liste_meuble3_d)
    listMeubles = generateList()
    buildRecyclerView()
}

private fun generateList(): MutableList&lt;Meuble&gt;{

    val list = mutableListOf&lt;Meuble&gt;()

       // to Add an Object Meuble(nom,prix,stock)

        val meuble = Meuble(R.drawable.fauteilgris, &quot;Gris&quot;,&quot;25000da&quot;,1)
        val meuble1 = Meuble(R.drawable.fauteuille1, &quot;&quot;,&quot;1000d&amp;&quot;,1)
        val meuble2 = Meuble(R.drawable.burau, &quot;Bureau&quot;,&quot;25000da&quot;,1)
        list.add(meuble)
        list.add(meuble1)
        list.add(meuble2)

    return list
}

fun buildRecyclerView() {
    mon_recycler.setHasFixedSize(true)
    mon_recycler.layoutManager = LinearLayoutManager(this)

    // NOTE: Here the lambda implicitly had an item of type Meuble passed.  We name it here but could have just used &quot;it&quot;.
    mon_recycler.adapter = MeubleAdapter(listMeubles.toTypedArray())
    { item -&gt;
        val intent3 = Intent(this, SceneformeActivity::class.java)
        intent3.putExtra(&quot;image_url&quot;,item.imageUrl)
        startActivity(intent3)
    }
 }

}
My Adapter Class .kt:

// Don&#39;t need to pass as a TypedArray - List is fine
class MeubleAdapter(private val exampleList: List&lt;Meuble&gt;,val listener: (Meuble)-&gt; Unit) :
    RecyclerView.Adapter&lt;MeubleAdapter.ExampleViewHolder&gt;() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.meuble_item,
            parent, false)
        return ExampleViewHolder(itemView)
    }
    override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {
        val currentItem = exampleList[position]
        holder.imageView.setImageResource(currentItem.imageResource)
        holder.textViewNomMeuble.text = currentItem.nom
        holder.textViewPrix.text = currentItem.prix
        holder.textViewStock.text = currentItem.stock.toString()

        holder.bind(exampleList[position],listener)
    }

    override fun getItemCount() = exampleList.size


    class ExampleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(meuble:Meuble,listener: (Meuble) -&gt; Unit)= with(itemView)
        {
            android.util.Log.i(&quot;XXXX&quot;,&quot;FCT Bind &quot;)
            setOnClickListener{(listener(meuble))}
        }

        val imageView: ImageView = itemView.image_view
        val textViewNomMeuble: TextView = itemView.nomMeuble
        val textViewStock: TextView = itemView.stock
        val textViewPrix: TextView = itemView.prix

    }
}

答案2

得分: 0

这是您要翻译的内容:

在主要代码部分中,我使用了这个解决方案,将点击的对象的名称(nom)传递到SceneFormActivity以获取引用,并在下一个活动中显示我的3D对象:

主代码部分:

val intent3 = Intent(this, SceneformeActivity::class.java)
intent3.putExtra("image_url", it.nom) // 使用 it.nom 获取点击对象的名称
startActivity(intent3)

在 SceneformeActivity 中:

private void initializeGallery() {
    String imageUrl = getIntent().getStringExtra("image_url"); // 将此从 getInt 更改为 getString 以获取名称
    LinearLayout gallery = findViewById(R.id.gallery_layout);
    String obj = imageUrl;
    switch (obj) {
        case "fauteilgris": { // case "String": 前一个活动(RecyclerView)中点击对象的名称
            ImageView andy = new ImageView(this);
            andy.setImageResource(R.drawable.fauteilgris);
            andy.setContentDescription("fauteuil Crème");
            andy.setOnClickListener(view -> { addObject(Uri.parse("foteuil.sfb")); });
            gallery.addView(andy);
        }
        break;
        case "banc": {
            ImageView andy = new ImageView(this);
            andy.setImageResource(R.drawable.banc);
            andy.setContentDescription("banc extérieur");
            andy.setOnClickListener(view -> { addObject(Uri.parse("Bench.sfb")); });
            gallery.addView(andy);
        }
        break;
        case "burau": {
            ImageView andy = new ImageView(this);
            andy.setImageResource(R.drawable.burau);
            andy.setContentDescription("bureau");
            andy.setOnClickListener(view -> { addObject(Uri.parse("bureau.sfb")); });
            gallery.addView(andy);
        }
        break;
        default:
            Toast.makeText(getApplicationContext(), "No Object", Toast.LENGTH_SHORT).show();
            break;
    }
}

请注意,我已经将代码中的HTML实体代码(如 &quot;&amp;)更正为正常的引号和符号。

英文:

So i used this solution,, i passed the name (nom) of my clicked object to the SceneFormActivity to get the reference and display my 3D object in the next activity:

code from main

   val intent3 = Intent(this, SceneformeActivity::class.java)
intent3.putExtra(&quot;image_url&quot;,it.nom) //  it.nom to get the name of the object clicked
startActivity(intent3)

and in SceneformeActivity :

 private void initializeGallery() {
String imageUrl = getIntent().getStringExtra(&quot;image_url&quot;); // changed this from getInt to getString to get the name
LinearLayout gallery = findViewById(R.id.gallery_layout);
String obj =imageUrl;   
switch (obj) {
case &quot;fauteilgris&quot;: { // case &quot;String&quot;: the name of the object clicked in the previous activity(RecyclerView)
ImageView andy = new ImageView(this);
andy.setImageResource(R.drawable.fauteilgris);
andy.setContentDescription(&quot;fauteuil Cr&#233;me&quot;);
andy.setOnClickListener(view -&gt;{addObject(Uri.parse(&quot;foteuil.sfb&quot;));});
gallery.addView(andy);
}
break;
case &quot;banc&quot;: {
ImageView andy = new ImageView(this);
andy.setImageResource(R.drawable.banc);
andy.setContentDescription(&quot;banc ext&#233;rieur&quot;);
andy.setOnClickListener(view -&gt;{addObject(Uri.parse(&quot;Bench.sfb&quot;));});
gallery.addView(andy);
}
break;
case &quot;burau&quot;: {
ImageView andy = new ImageView(this);
andy.setImageResource(R.drawable.burau);
andy.setContentDescription(&quot;bureau&quot;);
andy.setOnClickListener(view -&gt;{addObject(Uri.parse(&quot;bureau.sfb&quot;));});
gallery.addView(andy);
}
break;
default:Toast.makeText(getApplicationContext(),&quot;No Object&quot;,Toast.LENGTH_SHORT).show();
break;
}
}

huangapple
  • 本文由 发表于 2020年7月28日 23:35:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63137816.html
匿名

发表评论

匿名网友

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

确定